Vault  4.1
Public Member Functions | Static Public Member Functions | Static Public Attributes | Protected Member Functions | Static Protected Member Functions | Protected Attributes | Static Protected Attributes
VSocket Class Reference

VSocket is the class that defines a BSD or Winsock socket connection. More...

#include <vsocket.h>

Inheritance diagram for VSocket:
VListenerSocket

List of all members.

Public Member Functions

 VSocket ()
 The usual way to construct a VSocket is with the default constructor.
 VSocket (VSocketID id)
 The other way to construct a VSocket is to supply it an already-opened low-level socket ID.
virtual ~VSocket ()
 Destructor, cleans up by closing the socket.
virtual void connectToIPAddress (const VString &ipAddress, int portNumber)
 Connects to the server using the specified numeric IP address and port.
virtual void connectToHostName (const VString &hostName, int portNumber)
 Connects to the server using the specified host name and port; DNS resolution is performed on the host name to determine the IP addresses; the first resolved address is used.
virtual void connectToHostName (const VString &hostName, int portNumber, const VSocketConnectionStrategy &connectionStrategy)
 Connects to the server using the specified host name and port; DNS resolution is performed on the host name to determine the IP address.
void setSockID (VSocketID id)
 Associates this socket object with the specified socket id.
virtual void setHostIPAddressAndPort (const VString &hostIPAddress, int portNumber)
 Sets the host IP address and port for a subsequent connect() call.
VSocketID getSockID () const
 Returns the socket id.
VString getHostIPAddress () const
 Returns the IP address of the host to which this socket is connected or has been set via setHostIPAddressAndPort().
int getPortNumber () const
 Returns the port number on the host to which this socket is connected.
const VStringgetName () const
 Returns a string concatenating the host name and port number, for purposes of socket connection identification when debugging and logging.
void close ()
 Closes the socket.
void setLinger (int val)
 Sets the linger value for the socket.
void clearReadTimeOut ()
 Removes the read timeout setting for the socket.
void setReadTimeOut (const struct timeval &timeout)
 Sets the read timeout setting for the socket.
void clearWriteTimeOut ()
 Removes the write timeout setting for the socket.
void setWriteTimeOut (const struct timeval &timeout)
 Sets the write timeout setting for the socket.
void setDefaultSockOpt ()
 Sets the socket options to their default values.
Vs64 numBytesRead () const
 Returns the number of bytes that have been read from this socket.
Vs64 numBytesWritten () const
 Returns the number of bytes that have been written to this socket.
VDuration getIdleTime () const
 Returns the amount of time since the last read or write activity occurred on this socket.
virtual int available ()
 Returns the number of bytes that are available to be read on this socket.
virtual int read (Vu8 *buffer, int numBytesToRead)
 Reads data from the socket.
virtual int write (const Vu8 *buffer, int numBytesToWrite)
 Writes data to the socket.
virtual void flush ()
 Flushes any unwritten bytes to the socket.
virtual void discoverHostAndPort ()
 Sets the host name and port number properties of this socket by asking the lower level services to whom the socket is connected.
virtual void closeRead ()
 Shuts down just the read side of the connection.
virtual void closeWrite ()
 Shuts down just the write side of the connection.
virtual void setSockOpt (int level, int name, void *valuePtr, int valueLength)
 Sets a specified socket option.
void setIntSockOpt (int level, int name, int value)
 For "int" socket options, this helper function simplifies use of setSockOpt.

Static Public Member Functions

static void setPreferredNetworkInterface (const VString &interfaceName)
 This function lets you specify the preferred network interface to be used when locating the local IP address from among multiple available interfaces.
static void setPreferredLocalIPAddressPrefix (const VString &addressPrefix)
 This function lets you specify the preferred address to be used when locating the local IP address from among multiple available interfaces, by specifying part or all of the address.
static void getLocalHostIPAddress (VString &ipAddress, bool refresh=false)
 Returns the current processor's IP address.
static VNetworkInterfaceList enumerateNetworkInterfaces ()
 Returns a list of network interface info elements, by probing the network APIs and getting all of the AF_INET elements.
static VNetAddr ipAddressStringToNetAddr (const VString &ipAddress)
 Converts an IPv4 address string in dot notation to a 4-byte binary value that can be stored in a stream.
static void netAddrToIPAddressString (VNetAddr netAddr, VString &ipAddress)
 Converts a 4-byte binary IPv4 address value into a string in the dot notation format.
static VStringVector resolveHostName (const VString &hostName)
 Resolves a internet host name to one or more numeric IP address strings.
static bool isIPv4NumericString (const VString &ipAddress)
 Returns true if the supplied numeric IP address string appears to be in IPv4 dotted decimal format (n.n.n.n).
static bool isIPv6NumericString (const VString &ipAddress)
 Returns true if the supplied numeric IP address string appears to be in IPv6 format.
static bool isIPNumericString (const VString &ipAddress)
 Returns true if the supplied numeric IP address string appears to be in IPv6 or IPv4 format.

Static Public Attributes

static const VSocketID kNoSocketID = V_NO_SOCKET_ID_CONSTANT
 The sock id for a socket that is not connected.
static const int kDefaultBufferSize = 65535
 The default buffer size.
static const int kDefaultServiceType = 0x08
 The default service type.
static const int kDefaultNoDelay = 1
 The default nodelay value.

Protected Member Functions

virtual void _connectToIPAddress (const VString &ipAddress, int portNumber)
 Connects to the server.
virtual void _listen (const VString &bindAddress, int backlog)
 Starts listening for incoming connections.
int _platform_available ()
 Returns the number of bytes that are available to be read on this socket.

Static Protected Member Functions

static bool _platform_staticInit ()
 Used internally to initialize at startup.
static VNetworkInterfaceList _platform_enumerateNetworkInterfaces ()
 Platform-specific implementation of enumerateNetworkInterfaces() -- see doc comments for public API above.
static VString _platform_addrinfoToIPAddressString (const VString &hostName, const struct addrinfo *info)
 Returns a string representation of the specified addrinfo internet address.
static bool _platform_isSocketIDValid (VSocketID socketID)
 Returns true if the specified socket ID (e.g., returned from ::socket()) is valid.

Protected Attributes

VSocketID mSocketID
 The socket id.
VString mHostIPAddress
 The IP address of the host to which the socket is connected.
int mPortNumber
 The port number on the host to which the socket is connected.
bool mReadTimeOutActive
 True if reads should time out.
struct timeval mReadTimeOut
 The read timeout value, if used.
bool mWriteTimeOutActive
 True if writes should time out.
struct timeval mWriteTimeOut
 The write timeout value, if used.
bool mRequireReadAll
 True if we throw when read returns less than # bytes asked for.
Vs64 mNumBytesRead
 Number of bytes read from this socket.
Vs64 mNumBytesWritten
 Number of bytes written to this socket.
VInstant mLastEventTime
 Timestamp of last read or write.
VString mSocketName
 Returned by getName(), useful purely for logging and debugging.

Static Protected Attributes

static VString gPreferredNetworkInterfaceName
static VString gPreferredLocalIPAddressPrefix
static VString gCachedLocalHostIPAddress
static bool gStaticInited = VSocket::_platform_staticInit()
 Used internally to initialize at startup.

Detailed Description

VSocket is the class that defines a BSD or Winsock socket connection.

The basic way of using a client socket is to instantiate a VSocket (either directly or through a VSocketFactory), and then call connectToHostName() or connectToIPAddress() to connect to the desired server.

The basic way of using a server socket is to instantiate a VListenerThread and supplying it a VSocketFactory and a subclass of VSocketThreadFactory that will create your kind of VSocketThread to handle requests for a given connection.

The best way to do i/o on a socket once it's connected, is to instantiate a VSocketStream for the socket, and then instantiate the appropriate subclass of VIOStream to do well-typed reads and writes on the socket.

Here is how you would connect to a host, write a 32-bit integer in network byte order, receive a similar response, and clean up:

Vu32 exchangeSingleMessage(const VString& host, int port, Vu32 request)
{
VSocket socket;
socket.init(host, port);

VSocketStream stream(socket);
VBinaryIOStream io(stream);
Vu32 response;

io.writeU32(request);
io.flush();
response = io.readU32();

return response;
}

See also:
VSocketFactory
VSocketStream
VListenerSocket
VIOStream

FIXME: According to some docs I have found, the proper shutdown sequence for a connected socket is: 1. call shutdown(id, 1) // well, not 1, so SHUT_WR or SHUT_RDWR? SHUT_RD would seem to make the next step fail 2. loop on recv until it returns 0 or any error 3. call close (or closesocket + WSACleanup on Win (is WSACleanup gone in WS2?))

Definition at line 124 of file vsocket.h.


Constructor & Destructor Documentation

VSocket::VSocket ( )

The usual way to construct a VSocket is with the default constructor.

You then subsequently call one of the connect() functions to cause it to connect using the appropriate strategy. You could also call setSockID() with an already-open low-level socket ID.

Definition at line 220 of file vsocket.cpp.

VSocket::VSocket ( VSocketID  id)

The other way to construct a VSocket is to supply it an already-opened low-level socket ID.

The VSocket will take ownership of the socket, and unless you later call setSockID(kNoSocketID), it will close the underlying socket upon destruction or a call to close(). Constructs the object with an already-opened low-level socket connection identified by its ID.

Parameters:
idan existing already-opened low-level socket ID

Definition at line 236 of file vsocket.cpp.


Member Function Documentation

void VSocket::setPreferredNetworkInterface ( const VString interfaceName) [static]

This function lets you specify the preferred network interface to be used when locating the local IP address from among multiple available interfaces.

By default, "en0" (ethernet 0) is used. Note: This technique has no effect on Windows because the interfaces do not have names; you will need to use setPreferredLocalIPAddressPrefix() to achieve a similar effect.

Parameters:
interfaceNamethe name of a network interface to choose first as the local IP address when calling getLocalHostIPAddress()

Definition at line 28 of file vsocket.cpp.

void VSocket::setPreferredLocalIPAddressPrefix ( const VString addressPrefix) [static]

This function lets you specify the preferred address to be used when locating the local IP address from among multiple available interfaces, by specifying part or all of the address.

By default, there is no setting. If you set a value that is a complete address (for example, "10.40.5.210") then when you call getLocalHostIPAddress(), if that address exists on any interface it will be returned. If you set a value this is a partial/prefix of an address (for example, "10.40.") then the first interface whose address starts with that prefix will be returned; this may be useful in DHCP situations where the address changes but is somewhat consistent and different from the range of unwanted addresses (e.g., ethernet vs. wifi).

Parameters:
addressPrefixthe partial (prefix) or full local IP address to return if found on any interface when calling getLocalHostIPAddress()

Definition at line 33 of file vsocket.cpp.

void VSocket::getLocalHostIPAddress ( VString ipAddress,
bool  refresh = false 
) [static]

Returns the current processor's IP address.

If an error occurs, this function throws an exception containing the error code and message. Normally the first call gets the address, and later calls return a cached value; but you can pass refresh=true to force it to get the address again. If you have set a preferred interface by calling setPreferredNetworkInterface(), it will return that interface's address if found. Otherwise, the first interface's address is returned. The 127.0.0.1 loopback address is never returned.

Parameters:
ipAddressa string in which to place the host name
refreshset true to force the address to be re-obtained by the call; otherwise, we obtain it once and cache that to be returned on subsequent calls

Definition at line 38 of file vsocket.cpp.

References enumerateNetworkInterfaces(), and VString::isEmpty().

static VNetworkInterfaceList VSocket::enumerateNetworkInterfaces ( ) [inline, static]

Returns a list of network interface info elements, by probing the network APIs and getting all of the AF_INET elements.

Note that this may include multiple addresses if you have multiple network interfaces such as ethernet, wi-fi, etc. To obtain the "local host" IP address, you should call VSocket::getLocalHostIPAddress() rather than examining the results of this call, because it examines this information but takes into account the "preferred" interface that you can set with VSocket::setPreferredNetworkInterface().

Returns:
a list of zero or more network interfaces

Definition at line 179 of file vsocket.h.

References _platform_enumerateNetworkInterfaces().

VNetAddr VSocket::ipAddressStringToNetAddr ( const VString ipAddress) [static]

Converts an IPv4 address string in dot notation to a 4-byte binary value that can be stored in a stream.

Note that the return value is in network byte order by definition--think of it as an array of 4 bytes, not a 32-bit integer. Note that the VNetAddr data type should be avoided as much as possible, since it is IPv4 only.

Parameters:
ipAddressthe string to convert (must be in x.x.x.x notation)
Returns:
a 4-byte binary IPv4 address

Definition at line 58 of file vsocket.cpp.

void VSocket::netAddrToIPAddressString ( VNetAddr  netAddr,
VString ipAddress 
) [static]

Converts a 4-byte binary IPv4 address value into a string in the dot notation format.

Note that the input value is in network byte order by definition--think of it as an array of 4 bytes, not a 32-bit integer. Note that the VNetAddr data type should be avoided as much as possible, since it is IPv4 only.

Parameters:
netAddrthe 4-byte binary IPv4 address
ipAddressthe string in which to place the dot notation version of the address

Definition at line 64 of file vsocket.cpp.

References VString::copyFromCString().

VStringVector VSocket::resolveHostName ( const VString hostName) [static]

Resolves a internet host name to one or more numeric IP address strings.

Typically you will use this for a user-entered address that you want to then open a socket to. If multiple addresses are returned, you have to decide what strategy to use when connecting: a) use the first address only, b) try each one in sequence until you succeed, or c) try all or several in parallel and go with the fastest one to succed. Note that the returned strings may be in IPv4 dotted decimal format (n.n.n.n) or IPv6 format (x:x:x:x::n for example; there are several related forms, see RFC 2373). If there is an error, or if no addresses are resolved, this function will throw a VException. It will never return an empty vector.

Parameters:
hostNamethe host name to resolve; a numeric IP address is allowed and will presumably resolve to itself
Returns:
one or more numeric IP address strings that the OS has resolved the host name to; if there are none, a VException is thrown instead of returning an empty vector

Definition at line 93 of file vsocket.cpp.

References _platform_addrinfoToIPAddressString(), VString::chars(), VSystemError::getSocketError(), and NULL.

bool VSocket::isIPv4NumericString ( const VString ipAddress) [static]

Returns true if the supplied numeric IP address string appears to be in IPv4 dotted decimal format (n.n.n.n).

We just check basic contents: dots, decimals, and minimum length. RFC 2373 describes all the possible variants.

Parameters:
ipAddressa string to examine
Returns:
obvious

Definition at line 123 of file vsocket.cpp.

References VString::length().

bool VSocket::isIPv6NumericString ( const VString ipAddress) [static]

Returns true if the supplied numeric IP address string appears to be in IPv6 format.

We just check basic contents: colons, dots, hexadecimals, and minimum length.

Parameters:
ipAddressa string to examine
Returns:
obvious

Definition at line 155 of file vsocket.cpp.

References VString::length().

bool VSocket::isIPNumericString ( const VString ipAddress) [static]

Returns true if the supplied numeric IP address string appears to be in IPv6 or IPv4 format.

This is a combined check that is more efficient than calling both of the above checks separately since it only has to scan the string once. Use this to distinguish from a host name.

Parameters:
ipAddressa string to examine
Returns:
obvious

Definition at line 176 of file vsocket.cpp.

References VString::length().

void VSocket::connectToIPAddress ( const VString ipAddress,
int  portNumber 
) [virtual]

Connects to the server using the specified numeric IP address and port.

If the connection cannot be opened, a VException is thrown. This is also the API that the strategy object used by connectToHostName() will call (possibly on a temporary VSocket object) in order to establish a connection on a particular resolved IP address.

Parameters:
ipAddressthe IPv4 or IPv6 numeric address to connect to
portNumberthe port number to connect to

Definition at line 262 of file vsocket.cpp.

References _connectToIPAddress(), and setDefaultSockOpt().

void VSocket::connectToHostName ( const VString hostName,
int  portNumber 
) [virtual]

Connects to the server using the specified host name and port; DNS resolution is performed on the host name to determine the IP addresses; the first resolved address is used.

To choose a specific strategy for connecting to multiple resolved addresses, use the overloaded version of this API that takes a VSocketConnectionStrategy object. This version is equivalent to supplying a VSocketConnectionStrategySingle object. If the connection cannot be opened, a VException is thrown.

Parameters:
hostNamethe name to resolve and then connect to
portNumberthe port number to connect to

Definition at line 267 of file vsocket.cpp.

void VSocket::connectToHostName ( const VString hostName,
int  portNumber,
const VSocketConnectionStrategy connectionStrategy 
) [virtual]

Connects to the server using the specified host name and port; DNS resolution is performed on the host name to determine the IP address.

The supplied strategy determines how we connect when multiple addresses are returned by DNS resolution. If the connection cannot be opened, a VException is thrown.

Parameters:
hostNamethe name to resolve and then connect to
portNumberthe port number to connect to
connectionStrategya strategy for connecting to a host name that resolves to multiple IP addresses (
See also:
VSocketConnectionStrategySingle, VSocketConnectionStrategyLinear, VSocketConnectionStrategyThreaded)

Definition at line 271 of file vsocket.cpp.

References VSocketConnectionStrategy::connect().

void VSocket::setSockID ( VSocketID  id)

Associates this socket object with the specified socket id.

This is something you might use if you are managing sockets externally and want to have a socket object own a socket temporarily.

Note that this method does not cause a previous socket to be closed, nor does it update the name and port number properties of this object. If you want those things to happen, you can call close() and discoverHostAndPort() separately.

Parameters:
idthe socket id of the socket to manage

Definition at line 642 of file vsocket.cpp.

References mSocketID.

void VSocket::setHostIPAddressAndPort ( const VString hostIPAddress,
int  portNumber 
) [virtual]

Sets the host IP address and port for a subsequent connect() call.

Parameters:
hostIPAddressthe host IP address, an IPv4 or IPv6 numeric string
portNumberthe port number to connect to on the host

Definition at line 256 of file vsocket.cpp.

References VString::chars(), mHostIPAddress, mPortNumber, and mSocketName.

VSocketID VSocket::getSockID ( ) const

Returns the socket id.

Returns:
the socket id

Definition at line 638 of file vsocket.cpp.

References mSocketID.

VString VSocket::getHostIPAddress ( ) const

Returns the IP address of the host to which this socket is connected or has been set via setHostIPAddressAndPort().

Returns:
the host IP address; either an IPv4 or IPv6 numeric string

Definition at line 275 of file vsocket.cpp.

References mHostIPAddress.

int VSocket::getPortNumber ( ) const

Returns the port number on the host to which this socket is connected.

Returns:
the host's port number to which this socket is connected

Definition at line 279 of file vsocket.cpp.

References mPortNumber.

const VString& VSocket::getName ( ) const [inline]

Returns a string concatenating the host name and port number, for purposes of socket connection identification when debugging and logging.

Returns:
a string with this socket's address and port

Definition at line 341 of file vsocket.h.

References mSocketName.

void VSocket::close ( )

Closes the socket.

This terminates the connection.

Definition at line 283 of file vsocket.cpp.

References kNoSocketID, and mSocketID.

void VSocket::setLinger ( int  val)

Sets the linger value for the socket.

Parameters:
valthe linger value in seconds

Definition at line 299 of file vsocket.cpp.

References setSockOpt().

void VSocket::setReadTimeOut ( const struct timeval &  timeout)

Sets the read timeout setting for the socket.

Parameters:
timeoutthe read timeout value

Definition at line 318 of file vsocket.cpp.

References mReadTimeOut, and mReadTimeOutActive.

void VSocket::setWriteTimeOut ( const struct timeval &  timeout)

Sets the write timeout setting for the socket.

Parameters:
timeoutthe write timeout value

Definition at line 327 of file vsocket.cpp.

References mWriteTimeOut, and mWriteTimeOutActive.

Vs64 VSocket::numBytesRead ( ) const

Returns the number of bytes that have been read from this socket.

Returns:
the number of bytes read from this socket

Definition at line 355 of file vsocket.cpp.

References mNumBytesRead.

Vs64 VSocket::numBytesWritten ( ) const

Returns the number of bytes that have been written to this socket.

Returns:
the number of bytes written to this socket

Definition at line 359 of file vsocket.cpp.

References mNumBytesWritten.

virtual int VSocket::available ( ) [inline, virtual]

Returns the number of bytes that are available to be read on this socket.

If you do a read() on that number of bytes, you know that it will not block.

Returns:
the number of bytes currently available for reading

Definition at line 398 of file vsocket.h.

References _platform_available().

int VSocket::read ( Vu8 buffer,
int  numBytesToRead 
) [virtual]

Reads data from the socket.

If you don't have a read timeout set up for this socket, then read will block until all requested bytes have been read.

Parameters:
bufferthe buffer to read into
numBytesToReadthe number of bytes to read from the socket
Returns:
the number of bytes read

Definition at line 368 of file vsocket.cpp.

References _platform_isSocketIDValid(), VString::chars(), VSystemError::getSocketError(), VSystemError::isLikePosixError(), mLastEventTime, mNumBytesRead, mReadTimeOut, mReadTimeOutActive, mRequireReadAll, mSocketID, mSocketName, NULL, and VInstant::setNow().

int VSocket::write ( const Vu8 buffer,
int  numBytesToWrite 
) [virtual]

Writes data to the socket.

If you don't have a write timeout set up for this socket, then write will block until all requested bytes have been written.

Parameters:
bufferthe buffer to read out of
numBytesToWritethe number of bytes to write to the socket
Returns:
the number of bytes written

Definition at line 431 of file vsocket.cpp.

References _platform_isSocketIDValid(), VString::chars(), VSystemError::getSocketError(), VSystemError::isLikePosixError(), mNumBytesWritten, mSocketID, mSocketName, mWriteTimeOut, mWriteTimeOutActive, and NULL.

void VSocket::setSockOpt ( int  level,
int  name,
void *  valuePtr,
int  valueLength 
) [virtual]

Sets a specified socket option.

Parameters:
levelthe option level
namethe option name
valuePtra pointer to the new option value data
valueLengththe length of the data pointed to by valuePtr

Definition at line 517 of file vsocket.cpp.

References mSocketID.

void VSocket::setIntSockOpt ( int  level,
int  name,
int  value 
)

For "int" socket options, this helper function simplifies use of setSockOpt.

Parameters:
levelthe option level
namethe option name
valuethe option value

Definition at line 294 of file vsocket.cpp.

References setSockOpt().

void VSocket::_listen ( const VString bindAddress,
int  backlog 
) [protected, virtual]

Starts listening for incoming connections.

Only useful to call from a VListenerSocket subclass that exposes a public listen() API.

Parameters:
bindAddressif empty, the socket will bind to INADDR_ANY (usually a good default); if a value is supplied the socket will bind to the supplied IP address (can be useful on a multi-homed server)
backlogthe backlog value to supply to the ::listen() function

Definition at line 589 of file vsocket.cpp.

References _platform_isSocketIDValid(), VString::chars(), VSystemError::getSocketError(), VString::isEmpty(), kNoSocketID, mPortNumber, mSocketID, and mSocketName.

VString VSocket::_platform_addrinfoToIPAddressString ( const VString hostName,
const struct addrinfo *  info 
) [static, protected]

Returns a string representation of the specified addrinfo internet address.

It may be an IPv4 dotted decimal format (n.n.n.n) or IPv6 format. This function is used by resolveHostName() to convert each address it resolves.

Parameters:
hostNameoptional value to be used in an error message if we need to throw an exception
infothe addrinfo containing the low-level information about the address; you must only pass IPv4 (AF_INET) or IPv6 (AF_INET6) values; other types will result in an exception being thrown
Returns:
a string in IPv4 dotted decimal format (n.n.n.n) or IPv6 format

Definition at line 71 of file vsocket_platform.cpp.

References VString::buffer(), VString::chars(), VSystemError::getSocketError(), NULL, VString::postflight(), and VString::preflight().

bool VSocket::_platform_isSocketIDValid ( VSocketID  socketID) [static, protected]

Returns true if the specified socket ID (e.g., returned from ::socket()) is valid.

BSD and Winsock have different ranges of good values.

Parameters:
socketIDa platform-specific socket ID
Returns:
true if the socket ID is considered valid should an API such as ::socket() return it

Definition at line 94 of file vsocket_platform.cpp.

int VSocket::_platform_available ( ) [protected]

Returns the number of bytes that are available to be read on this socket.

If you do a read() on that number of bytes, you know that it will not block.

Returns:
the number of bytes currently available for reading

Definition at line 101 of file vsocket_platform.cpp.

References VString::chars(), VSystemError::getSocketError(), mSocketID, and mSocketName.


The documentation for this class was generated from the following files:

Copyright ©1997-2014 Trygve Isaacson. All rights reserved. This documentation was generated with Doxygen.