Bayonne2 / Common C++ 2 Framework
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
Public Types | Public Member Functions | Static Public Member Functions | Protected Types | Protected Member Functions | Protected Attributes | Static Protected Attributes | Private Member Functions | Private Attributes | Friends
Socket Class Reference

The Socket is used as the base for all Internet protocol services under Common C++. More...

#include <socket.h>

Inheritance diagram for Socket:
Inheritance graph
[legend]
Collaboration diagram for Socket:
Collaboration graph
[legend]

Public Types

enum  Family { IPV4 = AF_INET }
 
enum  Error {
  errSuccess = 0, errCreateFailed, errCopyFailed, errInput,
  errInputInterrupt, errResourceFailure, errOutput, errOutputInterrupt,
  errNotConnected, errConnectRefused, errConnectRejected, errConnectTimeout,
  errConnectFailed, errConnectInvalid, errConnectBusy, errConnectNoRoute,
  errBindingFailed, errBroadcastDenied, errRoutingDenied, errKeepaliveDenied,
  errServiceDenied, errServiceUnavailable, errMulticastDisabled, errTimeout,
  errNoDelay, errExtended, errLookupFail, errSearchErr,
  errInvalidValue
}
 
enum  Tos {
  tosLowDelay = 0, tosThroughput, tosReliability, tosMinCost,
  tosInvalid
}
 
enum  Pending { pendingInput, pendingOutput, pendingError }
 
typedef enum Family Family
 
typedef enum Error Error
 
typedef enum Tos Tos
 
typedef enum Pending Pending
 

Public Member Functions

virtual ~Socket ()
 The socket base class may be "thrown" as a result of an error, and the "catcher" may then choose to destroy the object. More...
 
Socketoperator= (const Socket &from)
 Sockets may also be duplicated by the assignment operator. More...
 
virtual IPV4Host getIPV4Sender (tpport_t *port=NULL) const
 May be used to examine the origin of data waiting in the socket receive queue. More...
 
IPV4Host getSender (tpport_t *port=NULL) const
 
IPV4Host getIPV4Peer (tpport_t *port=NULL) const
 Get the host address and port of the socket this socket is connected to. More...
 
IPV4Host getPeer (tpport_t *port=NULL) const
 
IPV4Host getIPV4Local (tpport_t *port=NULL) const
 Get the local address and port number this socket is currently bound to. More...
 
IPV4Host getLocal (tpport_t *port=NULL) const
 
IPV4Host getIPV4NAT (tpport_t *port=NULL) const
 Perform NAT table lookup for this socket. More...
 
IPV4Host getNAT (tpport_t *port) const
 
void setCompletion (bool immediate)
 Used to specify blocking mode for the socket. More...
 
Error setLinger (bool linger)
 Enable lingering sockets on close. More...
 
Error setKeepAlive (bool enable)
 Set the keep-alive status of this socket and if keep-alive messages will be sent. More...
 
Error setTypeOfService (Tos service)
 Set packet scheduling on platforms which support ip quality of service conventions. More...
 
bool isConnected (void) const
 Can test to see if this socket is "connected", and hence whether a "catch" can safely call getPeer(). More...
 
bool isActive (void) const
 Test to see if the socket is at least operating or if it is mearly initialized. More...
 
bool operator! () const
 Operator based testing to see if a socket is currently active. More...
 
bool isBroadcast (void) const
 Return if broadcast has been enabled for the specified socket. More...
 
bool isRouted (void) const
 Return if socket routing is enabled. More...
 
Error getErrorNumber (void) const
 Often used by a "catch" to fetch the last error of a thrown socket. More...
 
const char * getErrorString (void) const
 Often used by a "catch" to fetch the user set error string of a thrown socket, but only if EXTENDED error codes are used. More...
 
long getSystemError (void) const
 
const char * getSystemErrorString (void) const
 
virtual bool isPending (Pending pend, timeout_t timeout=TIMEOUT_INF)
 Get the status of pending operations. More...
 

Static Public Member Functions

static bool check (Family fam)
 See if a specific protocol family is available in the current runtime environment. More...
 

Protected Types

enum  State {
  INITIAL, AVAILABLE, BOUND, CONNECTED,
  CONNECTING, STREAM
}
 
typedef enum State State
 

Protected Member Functions

Error error (Error error, const char *err=NULL, long systemError=0) const
 This service is used to throw all socket errors which usually occur during the socket constructor. More...
 
void error (const char *err) const
 This service is used to throw application defined socket errors where the application specific error code is a string. More...
 
void setError (bool enable)
 This service is used to turn the error handler on or off for "throwing" exceptions by manipulating the thrown flag. More...
 
void endSocket (void)
 Used as the default destructor for ending a socket. More...
 
Error connectError (void)
 Used as a common handler for connection failure processing. More...
 
Error sendLimit (int limit=2048)
 Set the send limit. More...
 
Error receiveLimit (int limit=1)
 Set thr receive limit. More...
 
Error sendTimeout (timeout_t timer)
 Set the send timeout for sending raw network data. More...
 
Error receiveTimeout (timeout_t timer)
 Receive timeout for receiving raw network data. More...
 
Error sendBuffer (unsigned size)
 Set the protocol stack network kernel send buffer size associated with the socket. More...
 
Error receiveBuffer (unsigned size)
 Set the protocol stack network kernel receive buffer size associated with the socket. More...
 
Error bufferSize (unsigned size)
 Set the total protocol stack network kernel buffer size for both send and receive together. More...
 
Error setBroadcast (bool enable)
 Set the subnet broadcast flag for the socket. More...
 
Error setMulticastByFamily (bool enable, Family family=IPV4)
 Setting multicast binds the multicast interface used for the socket to the interface the socket itself has been implicitly bound to. More...
 
Error setLoopbackByFamily (bool enable, Family family=IPV4)
 Set the multicast loopback flag for the socket. More...
 
Error setTimeToLiveByFamily (unsigned char ttl, Family fam=IPV4)
 Set the multicast time to live for a multicast socket. More...
 
Error join (const IPV4Multicast &ia)
 Join a multicast group. More...
 
Error drop (const IPV4Multicast &ia)
 Drop membership from a multicast group. More...
 
Error setRouting (bool enable)
 Set the socket routing to indicate if outgoing messages should bypass normal routing (set false). More...
 
Error setNoDelay (bool enable)
 Enable/disable delaying packets (Nagle algorithm) More...
 
 Socket (int domain, int type, int protocol=0)
 An unconnected socket may be created directly on the local machine. More...
 
 Socket (SOCKET fd)
 A socket object may be created from a file descriptor when that descriptor was created either through a socket() or accept() call. More...
 
 Socket ()
 Create an inactive socket object for base constructors. More...
 
 Socket (const Socket &source)
 A socket can also be constructed from an already existing Socket object. More...
 
ssize_t readLine (char *buf, size_t len, timeout_t timeout=0)
 Process a logical input line from a socket descriptor directly. More...
 
virtual ssize_t readData (void *buf, size_t len, char separator=0, timeout_t t=0)
 Read in a block of len bytes with specific separator. More...
 
virtual ssize_t writeData (const void *buf, size_t len, timeout_t t=0)
 Write a block of len bytes to socket. More...
 

Protected Attributes

struct {
   bool   thrown: 1
 
   bool   broadcast: 1
 
   bool   route: 1
 
   bool   keepalive: 1
 
   bool   loopback: 1
 
   bool   multicast: 1
 
   bool   completion: 1
 
   bool   linger: 1
 
   unsigned   ttl: 8
 
flags
 
SOCKET volatile so
 the actual socket descriptor, in Windows, unlike posix it cannot be used as an file descriptor that way madness lies – jfc More...
 
State volatile state
 

Static Protected Attributes

static Mutex mutex
 

Private Member Functions

void setSocket (void)
 

Private Attributes

Error errid
 
const char * errstr
 
long syserr
 

Friends

SOCKET dupSocket (SOCKET s, Socket::State state)
 

Detailed Description

The Socket is used as the base for all Internet protocol services under Common C++.

A socket is a system resource (or winsock descriptor) that occupies a specific port address (and may be bound to a specific network interface) on the local machine. The socket may also be directly connected to a specific socket on a remote internet host.

This base class is not directly used, but is provided to offer properties common to other Common C++ socket classes, including the socket exception model and the ability to set socket properties such as QoS, "sockopts" properties like Dont-Route and Keep-Alive, etc.

Author
David Sugar dyfet.nosp@m.@ost.nosp@m.el.co.nosp@m.m base class of all sockets.

Definition at line 119 of file socket.h.

Member Typedef Documentation

typedef enum Error Socket::Error

Definition at line 163 of file socket.h.

typedef enum Family Socket::Family

Definition at line 129 of file socket.h.

typedef enum Pending Socket::Pending

Definition at line 179 of file socket.h.

typedef enum State Socket::State
protected

Definition at line 190 of file socket.h.

typedef enum Tos Socket::Tos

Definition at line 172 of file socket.h.

Member Enumeration Documentation

Enumerator
errSuccess 
errCreateFailed 
errCopyFailed 
errInput 
errInputInterrupt 
errResourceFailure 
errOutput 
errOutputInterrupt 
errNotConnected 
errConnectRefused 
errConnectRejected 
errConnectTimeout 
errConnectFailed 
errConnectInvalid 
errConnectBusy 
errConnectNoRoute 
errBindingFailed 
errBroadcastDenied 
errRoutingDenied 
errKeepaliveDenied 
errServiceDenied 
errServiceUnavailable 
errMulticastDisabled 
errTimeout 
errNoDelay 
errExtended 
errLookupFail 
errSearchErr 
errInvalidValue 

Definition at line 131 of file socket.h.

Enumerator
IPV4 

Definition at line 122 of file socket.h.

Enumerator
pendingInput 
pendingOutput 
pendingError 

Definition at line 174 of file socket.h.

enum Socket::State
protected
Enumerator
INITIAL 
AVAILABLE 
BOUND 
CONNECTED 
CONNECTING 
STREAM 

Definition at line 182 of file socket.h.

Enumerator
tosLowDelay 
tosThroughput 
tosReliability 
tosMinCost 
tosInvalid 

Definition at line 165 of file socket.h.

Constructor & Destructor Documentation

Socket::Socket ( int  domain,
int  type,
int  protocol = 0 
)
protected

An unconnected socket may be created directly on the local machine.

Sockets can occupy both the internet domain (AF_INET) and UNIX socket domain (AF_UNIX) under unix. The socket type (SOCK_STREAM, SOCK_DGRAM) and protocol may also be specified. If the socket cannot be created, an exception is thrown.

Parameters
domainsocket domain to use.
typebase type and protocol family of the socket.
protocolspecific protocol to apply.
Socket::Socket ( SOCKET  fd)
protected

A socket object may be created from a file descriptor when that descriptor was created either through a socket() or accept() call.

This constructor is mostly for internal use.

Parameters
fdfile descriptor of an already existing socket.
Socket::Socket ( )
protected

Create an inactive socket object for base constructors.

Socket::Socket ( const Socket source)
protected

A socket can also be constructed from an already existing Socket object.

On POSIX systems, the socket file descriptor is dup()'d. On Win32, DuplicateHandle() is used.

Parameters
sourceof existing socket to clone.
virtual Socket::~Socket ( )
virtual

The socket base class may be "thrown" as a result of an error, and the "catcher" may then choose to destroy the object.

By assuring the socket base class is a virtual destructor, we can assure the full object is properly terminated.

Member Function Documentation

Error Socket::bufferSize ( unsigned  size)
protected

Set the total protocol stack network kernel buffer size for both send and receive together.

Returns
errSuccess on success
Parameters
sizeof buffer.
static bool Socket::check ( Family  fam)
static

See if a specific protocol family is available in the current runtime environment.

Returns
true if family available.
Error Socket::connectError ( void  )
protected

Used as a common handler for connection failure processing.

Returns
correct failure code to apply.
Error Socket::drop ( const IPV4Multicast ia)
protected

Drop membership from a multicast group.

Returns
0 (errSuccess) on success, else error code.
Parameters
iaaddress of multicast group to drop.
void Socket::endSocket ( void  )
protected

Used as the default destructor for ending a socket.

This will cleanly terminate the socket connection. It is provided for use in derived virtual destructors.

Error Socket::error ( Error  error,
const char *  err = NULL,
long  systemError = 0 
) const
protected

This service is used to throw all socket errors which usually occur during the socket constructor.

Parameters
errordefined socket error id.
errstring or message to pass.
systemErrorthe system error# that caused the error
void Socket::error ( const char *  err) const
inlineprotected

This service is used to throw application defined socket errors where the application specific error code is a string.

Parameters
errstring or message to pass.

Definition at line 240 of file socket.h.

Error Socket::getErrorNumber ( void  ) const
inline

Often used by a "catch" to fetch the last error of a thrown socket.

Returns
error number of Error error.

Definition at line 668 of file socket.h.

const char* Socket::getErrorString ( void  ) const
inline

Often used by a "catch" to fetch the user set error string of a thrown socket, but only if EXTENDED error codes are used.

Returns
string for error message.

Definition at line 676 of file socket.h.

IPV4Host Socket::getIPV4Local ( tpport_t port = NULL) const

Get the local address and port number this socket is currently bound to.

Parameters
portptr to port number on local host.
Returns
host address of interface this socket is bound to.
IPV4Host Socket::getIPV4NAT ( tpport_t port = NULL) const

Perform NAT table lookup for this socket.

Used to allow an application to know the original ip:port pair the the client "thinks" it is connecting to. Used mostly to transparently impersonate a remote server/service.

On error, 0.0.0.0:0 is returned and one of the following error codes is set: errServiceUnavailable - if nat is not supported on the current platform or if it was not compiled; errLookupFail - if the nat syscall failed for some reason (extended error code); errSearchErr - if the socket does not have nat information (i.e. is not nated).

NAT lookup is supported on NetFilter for ipv4 and ipv6 (Linux), IPFilter for ipv4 (Solaris, *BSD except OpenBSD, HP-UX, etc.) and Packet Filter for ipv4 and ipv6 (OpenBSD). When using IPFilter or Packet Filter, the first NAT lookup must be performed as root (the NAT device is read only for root and is opened once, unless an error occurs). Permissions on the nat device may be changed to solve this.

Warning
When using IPFilter and Packet Filter, application data model must be the same as the running kernel (32/64 bits).
Parameters
portptr to NATed port number on local host.
Returns
NATed host address that this socket is related to.
IPV4Host Socket::getIPV4Peer ( tpport_t port = NULL) const

Get the host address and port of the socket this socket is connected to.

If the socket is currently not in a connected state, then a host address of 0.0.0.0 is returned.

Parameters
portptr to port number of remote socket.
Returns
host address of remote socket.
virtual IPV4Host Socket::getIPV4Sender ( tpport_t port = NULL) const
virtual

May be used to examine the origin of data waiting in the socket receive queue.

This can tell a TCP server where pending "connect" requests are coming from, or a UDP socket where it's next packet arrived from.

Parameters
portptr to port number of sender.
Returns
host address, test with "isInetAddress()".

Reimplemented in DCCPSocket.

IPV4Host Socket::getLocal ( tpport_t port = NULL) const
inline

Definition at line 539 of file socket.h.

IPV4Host Socket::getNAT ( tpport_t port) const
inline

Definition at line 575 of file socket.h.

IPV4Host Socket::getPeer ( tpport_t port = NULL) const
inline

Definition at line 523 of file socket.h.

IPV4Host Socket::getSender ( tpport_t port = NULL) const
inline

Definition at line 505 of file socket.h.

long Socket::getSystemError ( void  ) const
inline

Definition at line 678 of file socket.h.

const char* Socket::getSystemErrorString ( void  ) const
bool Socket::isActive ( void  ) const

Test to see if the socket is at least operating or if it is mearly initialized.

"initialized" sockets may be the result of failed constructors.

Returns
true if not in initial state.
bool Socket::isBroadcast ( void  ) const
inline

Return if broadcast has been enabled for the specified socket.

Returns
true if broadcast socket.

Definition at line 651 of file socket.h.

bool Socket::isConnected ( void  ) const

Can test to see if this socket is "connected", and hence whether a "catch" can safely call getPeer().

Of course, an unconnected socket will return a 0.0.0.0 address from getPeer() as well.

Returns
true when socket is connected to a peer.
virtual bool Socket::isPending ( Pending  pend,
timeout_t  timeout = TIMEOUT_INF 
)
virtual

Get the status of pending operations.

This can be used to examine if input or output is waiting, or if an error has occured on the descriptor.

Returns
true if ready, false on timeout.
Parameters
pendready check to perform.
timeoutin milliseconds, inf. if not specified.

Reimplemented in SimpleTCPStream, TCPStream, and UnixStream.

bool Socket::isRouted ( void  ) const
inline

Return if socket routing is enabled.

Returns
true if routing enabled.

Definition at line 659 of file socket.h.

Error Socket::join ( const IPV4Multicast ia)
protected

Join a multicast group.

Returns
0 (errSuccess) on success, else error code.
Parameters
iaaddress of multicast group to join.
bool Socket::operator! ( ) const

Operator based testing to see if a socket is currently active.

Socket& Socket::operator= ( const Socket from)

Sockets may also be duplicated by the assignment operator.

virtual ssize_t Socket::readData ( void *  buf,
size_t  len,
char  separator = 0,
timeout_t  t = 0 
)
protectedvirtual

Read in a block of len bytes with specific separator.

Can be zero, or any other char. If \n or \r, it's treated just like a readLine(). Otherwise it looks for the separator.

Parameters
bufpointer to byte allocation.
lenmaximum length to read.
separatorseparator for a particular ASCII character
ttimeout for pending data in milliseconds.
Returns
number of bytes actually read.
ssize_t Socket::readLine ( char *  buf,
size_t  len,
timeout_t  timeout = 0 
)
protected

Process a logical input line from a socket descriptor directly.

Parameters
bufpointer to string.
lenmaximum length to read.
timeoutfor pending data in milliseconds.
Returns
number of bytes actually read.
Error Socket::receiveBuffer ( unsigned  size)
protected

Set the protocol stack network kernel receive buffer size associated with the socket.

Returns
errSuccess on success, or error.
Parameters
sizeof buffer in bytes.
Error Socket::receiveLimit ( int  limit = 1)
protected

Set thr receive limit.

Error Socket::receiveTimeout ( timeout_t  timer)
protected

Receive timeout for receiving raw network data.

Returns
errSuccess if set.
Parameters
timervalue in milliseconds.
Error Socket::sendBuffer ( unsigned  size)
protected

Set the protocol stack network kernel send buffer size associated with the socket.

Returns
errSuccess on success, or error.
Parameters
sizeof buffer in bytes.
Error Socket::sendLimit ( int  limit = 2048)
protected

Set the send limit.

Error Socket::sendTimeout ( timeout_t  timer)
protected

Set the send timeout for sending raw network data.

Returns
errSuccess if set.
Parameters
timervalue in millisec.
Error Socket::setBroadcast ( bool  enable)
protected

Set the subnet broadcast flag for the socket.

This enables sending to a subnet and may require special image privileges depending on the operating system.

Returns
0 (errSuccess) on success, else error code.
Parameters
enablewhen set to true.
void Socket::setCompletion ( bool  immediate)

Used to specify blocking mode for the socket.

A socket can be made non-blocking by setting setCompletion(false) or set to block on all access with setCompletion(true). I do not believe this form of non-blocking socket I/O is supported in winsock, though it provides an alternate asynchronous set of socket services.

Parameters
immediatemode specify socket I/O call blocking mode.
void Socket::setError ( bool  enable)
inlineprotected

This service is used to turn the error handler on or off for "throwing" exceptions by manipulating the thrown flag.

Parameters
enabletrue to enable handler.

Definition at line 249 of file socket.h.

Error Socket::setKeepAlive ( bool  enable)

Set the keep-alive status of this socket and if keep-alive messages will be sent.

Returns
0 on success.
Parameters
enablekeep alive messages.
Error Socket::setLinger ( bool  linger)

Enable lingering sockets on close.

Parameters
lingerspecify linger enable.
Error Socket::setLoopbackByFamily ( bool  enable,
Family  family = IPV4 
)
protected

Set the multicast loopback flag for the socket.

Loopback enables a socket to hear what it is sending.

Returns
0 (errSuccess) on success, else error code.
Parameters
enablewhen set to true.
familyof protocol.
Error Socket::setMulticastByFamily ( bool  enable,
Family  family = IPV4 
)
protected

Setting multicast binds the multicast interface used for the socket to the interface the socket itself has been implicitly bound to.

It is also used as a check flag to make sure multicast is enabled before multicast operations are used.

Returns
0 (errSuccess) on success, else error code.
Parameters
enablewhen set to true.
familyof protocol.
Error Socket::setNoDelay ( bool  enable)
protected

Enable/disable delaying packets (Nagle algorithm)

Returns
0 on success.
Parameters
enabledisable Nagle algorithm when set to true.
Error Socket::setRouting ( bool  enable)
protected

Set the socket routing to indicate if outgoing messages should bypass normal routing (set false).

Returns
0 on success.
Parameters
enablenormal routing when set to true.
void Socket::setSocket ( void  )
private
Error Socket::setTimeToLiveByFamily ( unsigned char  ttl,
Family  fam = IPV4 
)
protected

Set the multicast time to live for a multicast socket.

Returns
0 (errSuccess) on success, else error code.
Parameters
ttltime to live.
famfamily of protocol.
Error Socket::setTypeOfService ( Tos  service)

Set packet scheduling on platforms which support ip quality of service conventions.

This effects how packets in the queue are scheduled through the interface.

Returns
0 on success, error code on failure.
Parameters
servicetype of service enumerated type.
virtual ssize_t Socket::writeData ( const void *  buf,
size_t  len,
timeout_t  t = 0 
)
protectedvirtual

Write a block of len bytes to socket.

Parameters
bufpointer to byte allocation.
lenmaximum length to write.
ttimeout for pending data in milliseconds.
Returns
number of bytes actually written.

Friends And Related Function Documentation

SOCKET dupSocket ( SOCKET  s,
Socket::State  state 
)
friend

Field Documentation

bool Socket::broadcast

Definition at line 206 of file socket.h.

bool Socket::completion

Definition at line 211 of file socket.h.

Error Socket::errid
mutableprivate

Definition at line 194 of file socket.h.

const char* Socket::errstr
mutableprivate

Definition at line 195 of file socket.h.

struct { ... } Socket::flags
bool Socket::keepalive

Definition at line 208 of file socket.h.

bool Socket::linger

Definition at line 212 of file socket.h.

bool Socket::loopback

Definition at line 209 of file socket.h.

bool Socket::multicast

Definition at line 210 of file socket.h.

Mutex Socket::mutex
staticprotected

Definition at line 202 of file socket.h.

bool Socket::route

Definition at line 207 of file socket.h.

SOCKET volatile Socket::so
protected

the actual socket descriptor, in Windows, unlike posix it cannot be used as an file descriptor that way madness lies – jfc

Definition at line 221 of file socket.h.

State volatile Socket::state
protected

Definition at line 222 of file socket.h.

long Socket::syserr
mutableprivate

Definition at line 196 of file socket.h.

bool Socket::thrown

Definition at line 205 of file socket.h.

unsigned Socket::ttl

Definition at line 213 of file socket.h.


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