MythTV  0.26-pre
Public Types | Public Member Functions | Protected Member Functions | Private Types | Private Member Functions | Static Private Member Functions | Private Attributes
MSocketDevice Class Reference

The MSocketDevice class provides a platform-independent low-level socket API. More...

#include <msocketdevice.h>

Inheritance diagram for MSocketDevice:
MBroadcastSocketDevice MMulticastSocketDevice MythSocket

List of all members.

Public Types

enum  Type { Stream, Datagram }
enum  Protocol { IPv4, IPv6, Unknown }
enum  Error {
  NoError, AlreadyBound, Inaccessible, NoResources,
  InternalError, Bug = InternalError, Impossible, NoFiles,
  ConnectionRefused, NetworkFailure, UnknownError
}

Public Member Functions

 MSocketDevice (Type type=Stream)
 MSocketDevice (Type type, Protocol protocol, int dummy)
 MSocketDevice (int socket, Type type)
virtual ~MSocketDevice ()
bool isValid () const
Type type () const
Protocol protocol () const
void setProtocol (Protocol protocol)
int socket () const
virtual void setSocket (int socket, Type type)
bool open (OpenMode mode)
bool open (int mode)
void close ()
bool flush ()
qint64 size () const
qint64 pos () const
bool seek (qint64)
bool atEnd () const
bool blocking () const
virtual void setBlocking (bool)
bool broadcast () const
virtual void setBroadcast (bool)
bool addressReusable () const
virtual void setAddressReusable (bool)
int receiveBufferSize () const
virtual void setReceiveBufferSize (uint)
int sendBufferSize () const
virtual void setSendBufferSize (uint)
bool keepalive () const
virtual void setKeepalive (bool)
virtual bool connect (const QHostAddress &, quint16)
virtual bool bind (const QHostAddress &, quint16)
virtual bool listen (int backlog)
virtual int accept ()
qint64 bytesAvailable () const
qint64 waitForMore (int msecs, bool *timeout=0) const
virtual qint64 writeBlock (const char *data, quint64 len, const QHostAddress &host, quint16 port)
qint64 writeBlock (const char *data, quint64 len)
qint64 readBlock (char *data, quint64 maxlen)
virtual quint16 port () const
virtual quint16 peerPort () const
virtual QHostAddress address () const
virtual QHostAddress peerAddress () const
Error error () const
bool isSequential () const
int createNewSocket ()

Protected Member Functions

void setError (Error err)
qint64 readData (char *data, qint64 maxlen)
qint64 writeData (const char *data, qint64 len)

Private Types

enum  Option {
  Broadcast, ReceiveBuffer, ReuseAddress, SendBuffer,
  Keepalive
}

Private Member Functions

int option (Option) const
virtual void setOption (Option, int)
void fetchConnectionParameters ()
void fetchPeerConnectionParameters ()
Protocol getProtocol () const
 MSocketDevice (const MSocketDevice &)
MSocketDeviceoperator= (const MSocketDevice &)

Static Private Member Functions

static void init ()

Private Attributes

int fd
Type t
quint16 p
QHostAddress a
quint16 pp
QHostAddress pa
MSocketDevice::Error e
MSocketDevicePrivated

Detailed Description

The MSocketDevice class provides a platform-independent low-level socket API.

This class provides a low level API for working with sockets. Users of this class are assumed to have networking experience. For most users the MSocket class provides a much easier and high level alternative, but certain things (like UDP) can't be done with MSocket and if you need a platform-independent API for those, MSocketDevice is the right choice.

The essential purpose of the class is to provide a QIODevice that works on sockets, wrapped in a platform-independent API.

When calling connect() or bind(), MSocketDevice detects the protocol family (IPv4, IPv6) automatically. Passing the protocol family to MSocketDevice's constructor or to setSocket() forces creation of a socket device of a specific protocol. If not set, the protocol will be detected at the first call to connect() or bind().

See also:
MSocket, QSocketNotifier, QHostAddress

Definition at line 54 of file msocketdevice.h.


Member Enumeration Documentation

This enum type describes the type of the socket: Stream a stream socket (TCP, usually) Datagram a datagram socket (UDP, usually)

Enumerator:
Stream 
Datagram 

Definition at line 58 of file msocketdevice.h.

This enum type describes the protocol family of the socket. Possible values are:

IPv4 The socket is an IPv4 socket. IPv6 The socket is an IPv6 socket. Unknown The protocol family of the socket is not known. This can happen if you use MSocketDevice with an already existing socket; it tries to determine the protocol family, but this can fail if the protocol family is not known to MSocketDevice.

See also:
protocol() setSocket()
Enumerator:
IPv4 
IPv6 
Unknown 

Definition at line 59 of file msocketdevice.h.

This enum type describes the error states of MSocketDevice.

NoError No error has occurred.

AlreadyBound The device is already bound, according to bind().

Inaccessible The operating system or firewall prohibited the action.

NoResources The operating system ran out of a resource.

InternalError An internal error occurred in MSocketDevice.

Impossible An attempt was made to do something which makes no sense. For example:

The libc close() closes the socket, but MSocketDevice is not aware of this. So when you call writeBlock(), the impossible happens.

NoFiles The operating system will not let MSocketDevice open another file.

ConnectionRefused A connection attempt was rejected by the peer.

NetworkFailure There is a network failure.

UnknownError The operating system did something unexpected.

Bug

Enumerator:
NoError 
AlreadyBound 
Inaccessible 
NoResources 
InternalError 
Bug 
Impossible 
NoFiles 
ConnectionRefused 
NetworkFailure 
UnknownError 

Definition at line 132 of file msocketdevice.h.

enum MSocketDevice::Option [private]
Enumerator:
Broadcast 
ReceiveBuffer 
ReuseAddress 
SendBuffer 
Keepalive 

Definition at line 170 of file msocketdevice.h.


Constructor & Destructor Documentation

Creates a MSocketDevice object for a stream or datagram socket.

The type argument must be either MSocketDevice::Stream for a reliable, connection-oriented TCP socket, or MSocketDevice::Datagram for an unreliable UDP socket. The socket protocol type is defaulting to unknown leaving it to connect() to determine if an IPv6 or IPv4 type is required.

See also:
blocking() protocol()

Definition at line 182 of file msocketdevice.cpp.

MSocketDevice::MSocketDevice ( Type  type,
Protocol  protocol,
int  dummy 
)

Creates a MSocketDevice object for a stream or datagram socket.

The type argument must be either MSocketDevice::Stream for a reliable, connection-oriented TCP socket, or MSocketDevice::Datagram for an unreliable UDP socket.

The protocol indicates whether the socket should be of type IPv4 or IPv6. Passing Unknown is not meaningful in this context and you should avoid using (it creates an IPv4 socket, but your code is not easily readable).

The argument dummy is necessary for compatibility with some compilers.

See also:
blocking() protocol()

Definition at line 211 of file msocketdevice.cpp.

MSocketDevice::MSocketDevice ( int  socket,
Type  type 
)

Creates a MSocketDevice object for the existing socket socket.

The type argument must match the actual socket type; use MSocketDevice::Stream for a reliable, connection-oriented TCP socket, or MSocketDevice::Datagram for an unreliable, connectionless UDP socket.

Definition at line 159 of file msocketdevice.cpp.

Destroys the socket device and closes the socket if it is open.

Definition at line 226 of file msocketdevice.cpp.


Member Function Documentation

Returns the socket type which is either MSocketDevice::Stream or MSocketDevice::Datagram.

See also:
socket()

Definition at line 256 of file msocketdevice.cpp.

Referenced by setSocket().

Returns the socket's protocol family, which is one of Unknown, IPv4, or IPv6.

MSocketDevice either creates a socket with a well known protocol family or it uses an already existing socket. In the first case, this function returns the protocol family it was constructed with. In the second case, it tries to determine the protocol family of the socket; if this fails, it returns Unknown.

See also:
Protocol setSocket()

Definition at line 273 of file msocketdevice.cpp.

Referenced by createNewSocket(), and setProtocol().

void MSocketDevice::setSocket ( int  socket,
Type  type 
) [virtual]

Sets the socket device to operate on the existing socket socket.

The type argument must match the actual socket type; use MSocketDevice::Stream for a reliable, connection-oriented TCP socket, or MSocketDevice::Datagram for an unreliable, connectionless UDP socket.

Any existing socket is closed.

See also:
isValid(), close()

Reimplemented in MythSocket.

Definition at line 310 of file msocketdevice.cpp.

Referenced by BufferedSocketDevice::BufferedSocketDevice(), connect(), MBroadcastSocketDevice::MBroadcastSocketDevice(), MMulticastSocketDevice::MMulticastSocketDevice(), MSocketDevice(), and SSDP::PerformSearch().

bool MSocketDevice::open ( OpenMode  mode)

Opens the socket using the specified QIODevice file mode. This function is called from the MSocketDevice constructors and from the setSocket() function. You should not call it yourself.

See also:
close()

Definition at line 341 of file msocketdevice.cpp.

Referenced by setSocket().

bool MSocketDevice::open ( int  mode) [inline]

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 76 of file msocketdevice.h.

Closes the socket and sets the socket identifier to -1 (invalid).

(This function ignores errors; if there are any then a file descriptor leakage might result. As far as we know, the only error that can arise is EBADF, and that would of course not cause leakage. There may be OS-specific errors that we haven't come across, however.)

See also:
open()

Reimplemented in MythSocket.

Definition at line 247 of file msocketdevice_unix.cpp.

Referenced by BufferedSocketDevice::Close(), connect(), readData(), setSocket(), writeData(), and ~MSocketDevice().

The current MSocketDevice implementation does not buffer at all, so this is a no-op. This function always returns true.

Definition at line 363 of file msocketdevice.cpp.

Referenced by MythSocket::writeStringList().

qint64 MSocketDevice::size ( void  ) const

The size is meaningless for a socket, therefore this function returns 0.

Definition at line 374 of file msocketdevice.cpp.

Referenced by MythSocket::writeStringList().

qint64 MSocketDevice::pos ( ) const

The read/write index is meaningless for a socket, therefore this function returns 0.

Definition at line 384 of file msocketdevice.cpp.

bool MSocketDevice::seek ( qint64  )

The read/write index is meaningless for a socket, therefore this function does nothing and returns true.

The offset parameter is ignored.

Definition at line 396 of file msocketdevice.cpp.

Returns true if no data is currently available at the socket; otherwise returns false.

Definition at line 408 of file msocketdevice.cpp.

Returns true if the socket is valid and in blocking mode; otherwise returns false.

Note that this function does not set error().

Warning:
On Windows, this function always returns true since the ioctlsocket() function is broken.
See also:
setBlocking(), isValid()

Definition at line 278 of file msocketdevice_unix.cpp.

Referenced by BufferedSocketDeviceRequest::IsBlocking().

void MSocketDevice::setBlocking ( bool  enable) [virtual]

Makes the socket blocking if enable is true or nonblocking if enable is false.

Sockets are blocking by default, but we recommend using nonblocking socket operations, especially for GUI programs that need to be responsive.

Warning:
On Windows, this function should be used with care since whenever you use a QSocketNotifier on Windows, the socket is immediately made nonblocking.
See also:
blocking(), isValid()

Definition at line 303 of file msocketdevice_unix.cpp.

Referenced by BufferedSocketDevice::BufferedSocketDevice(), UPnpEventTask::Execute(), HttpWorker::run(), UPNPSubscription::SendSubscribeRequest(), UPNPSubscription::SendUnsubscribeRequest(), BufferedSocketDeviceRequest::SetBlocking(), MythSocket::setSocket(), and SSDP::SSDP().

Returns true if this socket has the broadcast option set.

See also:
setBroadcast()

Definition at line 418 of file msocketdevice.cpp.

void MSocketDevice::setBroadcast ( bool  enable) [virtual]

Sets the broadcast option for this socket.

See also:
broadcast()

Definition at line 428 of file msocketdevice.cpp.

Referenced by WakeOnLAN().

Returns true if the address of this socket can be used by other sockets at the same time, and false if this socket claims exclusive ownership.

See also:
setAddressReusable()

Definition at line 440 of file msocketdevice.cpp.

Sets the address of this socket to be usable by other sockets too if enable is true, and to be used exclusively by this socket if enable is false.

When a socket is reusable, other sockets can use the same port number (and IP address), which is generally useful. Of course other sockets cannot use the same (address,port,peer-address,peer-port) 4-tuple as this socket, so there is no risk of confusing the two TCP connections.

See also:
addressReusable()

Definition at line 459 of file msocketdevice.cpp.

Referenced by BufferedSocketDevice::BufferedSocketDevice(), MythSocket::connect(), MBroadcastSocketDevice::MBroadcastSocketDevice(), and MMulticastSocketDevice::MMulticastSocketDevice().

Returns the size of the operating system receive buffer.

See also:
setReceiveBufferSize()

Definition at line 491 of file msocketdevice.cpp.

Sets the size of the operating system receive buffer to size.

The operating system receive buffer size effectively limits two things: how much data can be in transit at any one moment, and how much data can be received in one iteration of the main event loop.

The default is operating system-dependent. A socket that receives large amounts of data is probably best with a buffer size of 49152.

Definition at line 508 of file msocketdevice.cpp.

Referenced by MythSocket::connect().

Returns the size of the operating system send buffer.

See also:
setSendBufferSize()

Definition at line 519 of file msocketdevice.cpp.

Sets the size of the operating system send buffer to size.

The operating system send buffer size effectively limits how much data can be in transit at any one moment.

The default is operating system-dependent. A socket that sends large amounts of data is probably best with a buffer size of 49152.

Definition at line 535 of file msocketdevice.cpp.

Referenced by MythSocket::MythSocket().

Returns true if this socket has the keepalive option set.

See also:
setKeepalive()

Definition at line 470 of file msocketdevice.cpp.

void MSocketDevice::setKeepalive ( bool  enable) [virtual]

Sets the keepalive option for this socket.

See also:
keepalive()

Definition at line 480 of file msocketdevice.cpp.

Referenced by MythSocket::connect(), and MythSocket::setSocket().

bool MSocketDevice::connect ( const QHostAddress &  addr,
quint16  port 
) [virtual]

Connects to the IP address and port specified by addr and port. Returns true if it establishes a connection; otherwise returns false. If it returns false, error() explains why.

Note that error() commonly returns NoError for non-blocking sockets; this just means that you can call connect() again in a little while and it'll probably succeed.

Reimplemented in MythSocket.

Definition at line 502 of file msocketdevice_unix.cpp.

Referenced by BufferedSocketDevice::Connect(), and MythSocket::connect().

bool MSocketDevice::bind ( const QHostAddress &  address,
quint16  port 
) [virtual]

Assigns a name to an unnamed socket. The name is the host address address and the port number port. If the operation succeeds, bind() returns true; otherwise it returns false without changing what port() and address() return.

bind() is used by servers for setting up incoming connections. Call bind() before listen().

Definition at line 654 of file msocketdevice_unix.cpp.

Referenced by MBroadcastSocketDevice::MBroadcastSocketDevice(), MMulticastSocketDevice::MMulticastSocketDevice(), and SSDP::SSDP().

bool MSocketDevice::listen ( int  backlog) [virtual]

Specifies how many pending connections a server socket can have. Returns true if the operation was successful; otherwise returns false. A backlog value of 50 is quite common.

The listen() call only applies to sockets where type() is Stream, i.e. not to Datagram sockets. listen() must not be called before bind() or after accept().

See also:
bind(), accept()

Definition at line 756 of file msocketdevice_unix.cpp.

int MSocketDevice::accept ( void  ) [virtual]

Extracts the first connection from the queue of pending connections for this socket and returns a new socket identifier. Returns -1 if the operation failed.

See also:
bind(), listen()

Definition at line 778 of file msocketdevice_unix.cpp.

Returns the number of bytes available for reading, or -1 if an error occurred.

Warning:
On Microsoft Windows, we use the ioctlsocket() function to determine the number of bytes queued on the socket. According to Microsoft (KB Q125486), ioctlsocket() sometimes returns an incorrect number. The only safe way to determine the amount of data on the socket is to read it using readBlock(). QSocket has workarounds to deal with this problem.

Definition at line 890 of file msocketdevice_unix.cpp.

Referenced by atEnd(), MythSocket::closedByRemote(), SSDP::ProcessData(), MythSocketManager::ProcessRequest(), MainServer::ProcessRequest(), RemoteFile::Read(), BufferedSocketDevice::ReadBytes(), MythSocket::readStringList(), MythCoreContext::readyRead(), LCD::readyRead(), MythSocketThread::ReadyToBeRead(), RemoteFile::Reset(), waitForMore(), and RemoteFile::Write().

qint64 MSocketDevice::waitForMore ( int  msecs,
bool timeout = 0 
) const

Wait up to msecs milliseconds for more data to be available. If msecs is -1 the call will block indefinitely.

Returns the number of bytes available for reading, or -1 if an error occurred.

If timeout is non-null and no error occurred (i.e. it does not return -1): this function sets *timeout to true, if the reason for returning was that the timeout was reached; otherwise it sets timeout to false. This is useful to find out if the peer closed the connection.

Warning:
This is a blocking call and should be avoided in event driven applications.
See also:
bytesAvailable()

Definition at line 943 of file msocketdevice_unix.cpp.

Referenced by RemoteFile::Read(), MythSocket::readStringList(), BufferedSocketDevice::WaitForMore(), and writeData().

qint64 MSocketDevice::writeBlock ( const char *  data,
quint64  len,
const QHostAddress &  host,
quint16  port 
) [virtual]

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Writes len bytes to the socket from data and returns the number of bytes written. Returns -1 if an error occurred.

This is used for MSocketDevice::Datagram sockets. You must specify the host and port of the destination of the data.

Reimplemented in MMulticastSocketDevice.

Definition at line 1242 of file msocketdevice_unix.cpp.

Referenced by BufferedSocketDevice::Flush(), SSDP::PerformSearch(), UPnpSearchTask::SendMsg(), UPnpNotifyTask::SendNotifyMsg(), WakeOnLAN(), and BufferedSocketDevice::WriteBlockDirect().

qint64 MSocketDevice::writeBlock ( const char *  data,
quint64  len 
) [inline]

Reimplemented in MythSocket.

Definition at line 117 of file msocketdevice.h.

MSocketDevice::readBlock ( char *  data,
quint64  maxlen 
) [inline]

Reads maxlen bytes from the socket into data and returns the number of bytes read. Returns -1 if an error occurred. Returning 0 is not an error. For Stream sockets, 0 is returned when the remote host closes the connection. For Datagram sockets, 0 is a valid datagram size.

Reimplemented in MythSocket.

Definition at line 122 of file msocketdevice.h.

Referenced by SSDP::ProcessData(), and BufferedSocketDevice::ReadBytes().

quint16 MSocketDevice::port ( ) const [virtual]

Returns the port number of this socket device. This may be 0 for a while, but is set to something sensible as soon as a sensible value is available.

Note that Qt always uses native byte order, i.e. 67 is 67 in Qt; there is no need to call htons().

Reimplemented in MMulticastSocketDevice, and MBroadcastSocketDevice.

Definition at line 549 of file msocketdevice.cpp.

Referenced by connect(), BufferedSocketDevice::Port(), and UPnpNotifyTask::SendNotifyMsg().

quint16 MSocketDevice::peerPort ( ) const [virtual]

Returns the port number of the port this socket device is connected to. This may be 0 for a while, but is set to something sensible as soon as a sensible value is available.

Note that for Datagram sockets, this is the source port of the last packet received, and that it is in native byte order.

Definition at line 1435 of file msocketdevice_unix.cpp.

Referenced by MythCoreContext::GetMasterHostPrefix(), BufferedSocketDevice::PeerPort(), and SSDP::ProcessData().

QHostAddress MSocketDevice::address ( ) const [virtual]

Returns the address of this socket device. This may be 0.0.0.0 for a while, but is set to something sensible as soon as a sensible value is available.

Reimplemented in MMulticastSocketDevice, and MBroadcastSocketDevice.

Definition at line 560 of file msocketdevice.cpp.

Referenced by BufferedSocketDevice::Address(), BufferedSocketDeviceRequest::GetHostAddress(), and UPnpNotifyTask::SendNotifyMsg().

QHostAddress MSocketDevice::peerAddress ( ) const [virtual]

Returns the address of the port this socket device is connected to. This may be 0.0.0.0 for a while, but is set to something sensible as soon as a sensible value is available.

Note that for Datagram sockets, this is the source port of the last packet received.

Definition at line 1449 of file msocketdevice_unix.cpp.

Referenced by MythCoreContext::GetMasterHostPrefix(), BufferedSocketDeviceRequest::GetPeerAddress(), BufferedSocketDevice::PeerAddress(), and SSDP::ProcessData().

bool MSocketDevice::isSequential ( ) const [inline]

Definition at line 148 of file msocketdevice.h.

Creates a new socket identifier. Returns -1 if there is a failure to create the new identifier; error() explains why.

See also:
setSocket()

Definition at line 185 of file msocketdevice_unix.cpp.

Referenced by connect(), MBroadcastSocketDevice::MBroadcastSocketDevice(), MMulticastSocketDevice::MMulticastSocketDevice(), MSocketDevice(), and SSDP::PerformSearch().

void MSocketDevice::setError ( Error  err) [protected]

Allows subclasses to set the error state to err.

Definition at line 591 of file msocketdevice.cpp.

qint64 MSocketDevice::readData ( char *  data,
qint64  maxlen 
) [protected]

Reads maxlen bytes from the socket into data and returns the number of bytes read. Returns -1 if an error occurred.

Definition at line 984 of file msocketdevice_unix.cpp.

qint64 MSocketDevice::writeData ( const char *  data,
qint64  len 
) [protected]

Writes len bytes to the socket from data and returns the number of bytes written. Returns -1 if an error occurred.

This is used for MSocketDevice::Stream sockets.

Definition at line 1121 of file msocketdevice_unix.cpp.

int MSocketDevice::option ( Option  opt) const [private]

Returns the value of the socket option opt.

Definition at line 360 of file msocketdevice_unix.cpp.

Referenced by addressReusable(), broadcast(), keepalive(), receiveBufferSize(), and sendBufferSize().

void MSocketDevice::setOption ( Option  opt,
int  v 
) [private, virtual]

Sets the socket option opt to v.

Definition at line 435 of file msocketdevice_unix.cpp.

Referenced by setAddressReusable(), setBroadcast(), setKeepalive(), setReceiveBufferSize(), and setSendBufferSize().

Fetches information about both ends of the connection: whatever is available.

Definition at line 1391 of file msocketdevice_unix.cpp.

Referenced by bind(), close(), connect(), and setSocket().

Definition at line 1443 of file msocketdevice_win.cpp.

void MSocketDevice::init ( ) [static, private]

Definition at line 120 of file msocketdevice_unix.cpp.

Referenced by MSocketDevice().

Definition at line 125 of file msocketdevice_unix.cpp.

Referenced by protocol().

MSocketDevice& MSocketDevice::operator= ( const MSocketDevice ) [private]

Member Data Documentation

Definition at line 162 of file msocketdevice.h.

Referenced by connect(), createNewSocket(), readData(), setSocket(), type(), and writeBlock().

quint16 MSocketDevice::p [private]

Definition at line 163 of file msocketdevice.h.

Referenced by fetchConnectionParameters(), and port().

QHostAddress MSocketDevice::a [private]

Definition at line 164 of file msocketdevice.h.

Referenced by address(), and fetchConnectionParameters().

quint16 MSocketDevice::pp [private]
QHostAddress MSocketDevice::pa [private]

Definition at line 168 of file msocketdevice.h.

Referenced by protocol(), setProtocol(), setSocket(), and ~MSocketDevice().


The documentation for this class was generated from the following files:
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends