Logo
~Sockets~
~Examples~
~Contact~


Socket Class Reference
[Basic sockets]

Socket base class. More...

#include <Socket.h>

Inheritance diagram for Socket:
Collaboration diagram for Socket:

List of all members.


Public Member Functions

 Socket (ISocketHandler &)
 Socket mode flags.
virtual ~Socket ()
virtual SocketCreate ()
 Socket class instantiation method.
ISocketHandlerHandler () const
 Returns reference to sockethandler that owns the socket.
ISocketHandlerMasterHandler () const
 Returns reference to sockethandler that owns the socket.
virtual void Init ()
 Called by ListenSocket after accept but before socket is added to handler.
SOCKET CreateSocket (int af, int type, const std::string &protocol="")
 Create a socket file descriptor.
void Attach (SOCKET s)
 Assign this socket a file descriptor created by a call to socket() or otherwise.
SOCKET GetSocket ()
 Return file descriptor assigned to this socket.
virtual int Close ()
 Close connection immediately - internal use.
void Set (bool bRead, bool bWrite, bool bException=true)
 Add file descriptor to sockethandler fd_set's.
virtual bool Ready ()
 Returns true when socket file descriptor is valid and socket is not about to be closed.
SocketGetParent ()
 Returns pointer to ListenSocket that created this instance on an incoming connection.
void SetParent (Socket *)
 Used by ListenSocket to set parent pointer of newly created socket instance.
virtual port_t GetPort ()
 Get listening port from ListenSocket<>.
bool SetNonblocking (bool)
 Set socket non-block operation.
bool SetNonblocking (bool, SOCKET)
 Set socket non-block operation.
time_t Uptime ()
 Total lifetime of instance.
void SetClientRemoteAddress (SocketAddress &)
 Set address/port of last connect() call.
std::auto_ptr< SocketAddressGetClientRemoteAddress ()
 Get address/port of last connect() call.
virtual void SendBuf (const char *, size_t, int=0)
 Common interface for SendBuf used by Tcp and Udp sockets.
virtual void Send (const std::string &, int=0)
 Common interface for Send used by Tcp and Udp sockets.
virtual uint64_t GetBytesSent (bool clear=false)
 Outgoing traffic counter.
virtual uint64_t GetBytesReceived (bool clear=false)
 Incoming traffic counter.
void SetTimeout (time_t secs)
 Enable timeout control.
bool Timeout (time_t tnow)
 Check timeout.
void SetRemoteAddress (SocketAddress &)
 Used by ListenSocket.
port_t GetSockPort ()
 Returns local port number for bound socket file descriptor.
ipaddr_t GetSockIP4 ()
 Returns local ipv4 address for bound socket file descriptor.
std::string GetSockAddress ()
 Returns local ipv4 address as text for bound socket file descriptor.
void SetTrafficMonitor (IFile *p)
 Write traffic to an IFile.
Event callbacks
virtual void OnRead ()
 Called when there is something to be read from the file descriptor.
virtual void OnWrite ()
 Called when there is room for another write on the file descriptor.
virtual void OnException ()
 Called on socket exception.
virtual void OnDelete ()
 Called before a socket class is deleted by the ISocketHandler.
virtual void OnConnect ()
 Called when a connection has completed.
virtual void OnAccept ()
 Called when an incoming connection has been completed.
virtual void OnLine (const std::string &)
 Called when a complete line has been read and the socket is in line protocol mode.
virtual void OnConnectFailed ()
 Called on connect timeout (5s).
virtual void OnOptions (int family, int type, int protocol, SOCKET s)=0
 Called when a client socket is created, to set socket options.
virtual bool OnConnectRetry ()
 Connection retry callback - return false to abort connection attempts.
virtual void OnReconnect ()
 a reconnect has been made
virtual void OnDisconnect ()
 TcpSocket: When a disconnect has been detected (recv/SSL_read returns 0 bytes).
virtual void OnDisconnect (short info, int code)
 TcpSocket: When a disconnect has been detected (recv/SSL_read returns 0 bytes).
virtual void OnTimeout ()
 Timeout callback.
virtual void OnConnectTimeout ()
 Connection timeout.
Socket mode flags, set/reset
void SetDeleteByHandler (bool=true)
 Set delete by handler true when you want the sockethandler to delete the socket instance after use.
bool DeleteByHandler ()
 Check delete by handler flag.
void SetCloseAndDelete (bool=true)
 Set close and delete to terminate the connection.
bool CloseAndDelete ()
 Check close and delete flag.
time_t TimeSinceClose ()
 Return number of seconds since socket was ordered to close.
void DisableRead (bool x=true)
 Ignore read events for an output only socket.
bool IsDisableRead ()
 Check ignore read events flag.
void SetConnected (bool=true)
 Set connected status.
bool IsConnected ()
 Check connected status.
void SetLost ()
 Connection lost - error while reading/writing from a socket - TcpSocket only.
bool Lost ()
 Check connection lost status flag, used by TcpSocket only.
void SetErasedByHandler (bool x=true)
 Set flag indicating the socket is being actively deleted by the sockethandler.
bool ErasedByHandler ()
 Get value of flag indicating socket is deleted by sockethandler.
Information about remote connection
std::auto_ptr< SocketAddressGetRemoteSocketAddress ()
 Returns address of remote end.
ipaddr_t GetRemoteIP4 ()
 Returns address of remote end: ipv4.
port_t GetRemotePort ()
 Returns remote port number: ipv4 and ipv6.
std::string GetRemoteAddress ()
 Returns remote ip as string? ipv4 and ipv6.
std::string GetRemoteHostname ()
 ipv4 and ipv6(not implemented)
IP options
When an ip or socket option is available on all of the operating systems I'm testing on (linux 2.4.x, _win32, macosx, solaris9 intel) they are not checked with an ifdef below.

This might cause a compile error on other operating systems.

bool SetIpOptions (const void *p, socklen_t len)
bool SetIpTOS (unsigned char tos)
unsigned char IpTOS ()
bool SetIpTTL (int ttl)
int IpTTL ()
bool SetIpHdrincl (bool x=true)
bool SetIpMulticastTTL (int)
int IpMulticastTTL ()
bool SetMulticastLoop (bool x=true)
bool IpAddMembership (struct ip_mreq &)
bool IpDropMembership (struct ip_mreq &)
Socket Options
bool SoAcceptconn ()
bool SetSoBroadcast (bool x=true)
bool SetSoDebug (bool x=true)
int SoError ()
bool SetSoDontroute (bool x=true)
bool SetSoLinger (int onoff, int linger)
bool SetSoOobinline (bool x=true)
bool SetSoRcvlowat (int)
bool SetSoSndlowat (int)
bool SetSoRcvtimeo (struct timeval &)
bool SetSoSndtimeo (struct timeval &)
bool SetSoRcvbuf (int)
int SoRcvbuf ()
bool SetSoSndbuf (int)
int SoSndbuf ()
int SoType ()
bool SetSoReuseaddr (bool x=true)
bool SetSoKeepalive (bool x=true)
SSL Support
virtual void OnSSLConnect ()
 SSL client/server support - internal use.
virtual void OnSSLAccept ()
 SSL client/server support - internal use.
virtual void OnSSLConnectFailed ()
 SSL negotiation failed for client connect.
virtual void OnSSLAcceptFailed ()
 SSL negotiation failed for server accept.
virtual bool SSLNegotiate ()
 new SSL support
bool IsSSL ()
 Check if SSL is Enabled for this TcpSocket.
void EnableSSL (bool x=true)
 Enable SSL operation for a TcpSocket.
bool IsSSLNegotiate ()
 Still negotiating ssl connection.
void SetSSLNegotiate (bool x=true)
 Set flag indicating ssl handshaking still in progress.
bool IsSSLServer ()
 OnAccept called with SSL Enabled.
void SetSSLServer (bool x=true)
 Set flag indicating that this is a TcpSocket with incoming SSL connection.
virtual SSL_CTX * GetSslContext ()
 SSL; Get pointer to ssl context structure.
virtual SSL * GetSsl ()
 SSL; Get pointer to ssl structure.
Connection Pool
void SetIsClient ()
 Client = connecting TcpSocket.
void SetSocketType (int x)
 Socket type from socket() call.
int GetSocketType ()
 Socket type from socket() call.
void SetSocketProtocol (const std::string &x)
 Protocol type from socket() call.
const std::string & GetSocketProtocol ()
 Protocol type from socket() call.
void SetRetain ()
 Instruct a client socket to stay open in the connection pool after use.
bool Retain ()
 Check retain flag.
void CopyConnection (Socket *sock)
 Copy connection parameters from sock.
Socks4 support
virtual void OnSocks4Connect ()
 Socks4 client support internal use.
virtual void OnSocks4ConnectFailed ()
 Socks4 client support internal use.
virtual bool OnSocks4Read ()
 Socks4 client support internal use.
bool Socks4 ()
 Called when the last write caused the tcp output buffer to become empty.
void SetSocks4 (bool x=true)
 Set flag indicating Socks4 handshaking in progress.
void SetSocks4Host (ipaddr_t a)
 Set socks4 server host address to use.
void SetSocks4Host (const std::string &)
 Set socks4 server hostname to use.
void SetSocks4Port (port_t p)
 Socks4 server port to use.
void SetSocks4Userid (const std::string &x)
 Provide a socks4 userid if required by the socks4 server.
ipaddr_t GetSocks4Host ()
 Get the ip address of socks4 server to use.
port_t GetSocks4Port ()
 Get the socks4 server port to use.
const std::string & GetSocks4Userid ()
 Get socks4 userid.
Asynchronous Resolver
int Resolve (const std::string &host, port_t port=0)
 Request an asynchronous dns resolution.
virtual void OnResolved (int id, ipaddr_t a, port_t port)
 Callback returning a resolved address.
int Resolve (ipaddr_t a)
 Request asynchronous reverse dns lookup.
virtual void OnReverseResolved (int id, const std::string &name)
 Callback returning reverse resolve results.
virtual void OnResolveFailed (int id)
 Callback indicating failed dns lookup.
Thread Support
virtual void OnDetached ()
 Callback fires when a new socket thread has started and this socket is ready for operation again.
void SetDetach (bool x=true)
 Internal use.
bool IsDetach ()
 Check detach flag.
void SetDetached (bool x=true)
 Internal use.
const bool IsDetached () const
 Check detached flag.
bool Detach ()
 Order this socket to start its own thread and call OnDetached when ready for operation.
void SetSlaveHandler (ISocketHandler *)
 Store the slave sockethandler pointer.
void DetachSocket ()
 Create new thread for this socket to run detached in.

Protected Member Functions

 Socket ()
 default constructor not available
 Socket (const Socket &s)
 copy constructor not available
Socketoperator= (const Socket &)
 assignment operator not available.
IFileGetTrafficMonitor ()
 All traffic will be written to this IFile, if set.

Private Attributes

ISocketHandlerm_handler
 Reference of ISocketHandler in control of this socket.
SOCKET m_socket
 File descriptor.
bool m_bDel
 Delete by handler flag.
bool m_bClose
 Close and delete flag.
time_t m_tCreate
 Time in seconds when this socket was created.
Socketm_parent
 Pointer to ListenSocket class, valid for incoming sockets.
bool m_b_disable_read
 Disable checking for read events.
bool m_connected
 Socket is connected (tcp/udp).
bool m_b_erased_by_handler
 Set by handler before delete.
time_t m_tClose
 Time in seconds when ordered to close.
std::auto_ptr< SocketAddressm_client_remote_address
 Address of last connect().
std::auto_ptr< SocketAddressm_remote_address
 Remote end address.
IFilem_traffic_monitor
time_t m_timeout_start
 Set by SetTimeout.
time_t m_timeout_limit
 Defined by SetTimeout.
bool m_bLost
 connection lost
bool m_b_enable_ssl
 Enable SSL for this TcpSocket.
bool m_b_ssl
 ssl negotiation mode (TcpSocket)
bool m_b_ssl_server
 True if this is an incoming ssl TcpSocket connection.
int m_socket_type
 Type of socket, from socket() call.
std::string m_socket_protocol
 Protocol, from socket() call.
bool m_bClient
 only client connections are pooled
bool m_bRetain
 keep connection on close
bool m_bSocks4
 socks4 negotiation mode (TcpSocket)
ipaddr_t m_socks4_host
 socks4 server address
port_t m_socks4_port
 socks4 server port number
std::string m_socks4_userid
 socks4 server usedid
bool m_detach
 Socket ordered to detach flag.
bool m_detached
 Socket has been detached.
SocketThreadm_pThread
 Detach socket thread class pointer.
ISocketHandlerm_slave_handler
 Actual sockethandler while detached.

Classes

class  SocketThread
 Detached socket run thread. More...

Detailed Description

Socket base class.

Definition at line 60 of file Socket.h.


Constructor & Destructor Documentation

Socket::Socket ( ISocketHandler h  ) 

Socket mode flags.

"Default" constructor

Definition at line 70 of file Socket.cpp.

00071   :m_flags(0)
00072 :m_handler(h)
00073 ,m_socket( INVALID_SOCKET )
00074 ,m_bDel(false)
00075 ,m_bClose(false)
00076 ,m_tCreate(time(NULL))
00077 ,m_parent(NULL)
00078 ,m_b_disable_read(false)
00079 ,m_connected(false)
00080 ,m_b_erased_by_handler(false)
00081 ,m_tClose(0)
00082 ,m_client_remote_address(NULL)
00083 ,m_remote_address(NULL)
00084 ,m_traffic_monitor(NULL)
00085 ,m_bLost(false)
00086 #ifdef HAVE_OPENSSL
00087 ,m_b_enable_ssl(false)
00088 ,m_b_ssl(false)
00089 ,m_b_ssl_server(false)
00090 #endif
00091 #ifdef ENABLE_IPV6
00092 ,m_ipv6(false)
00093 #endif
00094 #ifdef ENABLE_POOL
00095 ,m_socket_type(0)
00096 ,m_bClient(false)
00097 ,m_bRetain(false)
00098 #endif
00099 #ifdef ENABLE_SOCKS4
00100 ,m_bSocks4(false)
00101 ,m_socks4_host(h.GetSocks4Host())
00102 ,m_socks4_port(h.GetSocks4Port())
00103 ,m_socks4_userid(h.GetSocks4Userid())
00104 #endif
00105 #ifdef ENABLE_DETACH
00106 ,m_detach(false)
00107 ,m_detached(false)
00108 ,m_pThread(NULL)
00109 ,m_slave_handler(NULL)
00110 #endif
00111 {
00112 }

Socket::~Socket (  )  [virtual]

Definition at line 115 of file Socket.cpp.

References Close(), Handler(), INVALID_SOCKET, m_bRetain, m_socket, and ISocketHandler::Remove().

00116 {
00117         Handler().Remove(this);
00118         if (m_socket != INVALID_SOCKET
00119 #ifdef ENABLE_POOL
00120                  && !m_bRetain
00121 #endif
00122                 )
00123         {
00124                 Close();
00125         }
00126 }

Socket::Socket (  )  [inline, protected]

default constructor not available

Definition at line 674 of file Socket.h.

00674 : m_handler(m_handler) {}

Socket::Socket ( const Socket s  )  [inline, protected]

copy constructor not available

Definition at line 676 of file Socket.h.

00676 : m_handler(s.m_handler) {}


Member Function Documentation

virtual Socket* Socket::Create (  )  [inline, virtual]

Socket class instantiation method.

Used when a "non-standard" constructor needs to be used for the socket class. Note: the socket class still needs the "default" constructor with one ISocketHandler& as input parameter.

Definition at line 147 of file Socket.h.

Referenced by SctpSocket::PeelOff().

00147 { return NULL; }

ISocketHandler & Socket::Handler (  )  const

Returns reference to sockethandler that owns the socket.

If the socket is detached, this is a reference to the slave sockethandler.

Definition at line 292 of file Socket.cpp.

References IsDetached(), m_handler, and m_slave_handler.

Referenced by SctpSocket::AddAddress(), SctpSocket::AddConnection(), HttpPostSocket::AddFile(), UdpSocket::AddMulticastMembership(), UdpSocket::Bind(), SctpSocket::Bind(), TcpSocket::Close(), Close(), CreateSocket(), HttpdSocket::datetime2httpdate(), UdpSocket::DropMulticastMembership(), GetClientRemoteAddress(), SctpSocket::getladdrs(), UdpSocket::GetMulticastTTL(), SctpSocket::getpaddrs(), GetPort(), GetRemoteIP4(), TcpSocket::GetSsl(), TcpSocket::GetSslContext(), HttpGetSocket::HttpGetSocket(), HttpDebugSocket::Init(), TcpSocket::InitializeContext(), TcpSocket::InitSSLServer(), IpAddMembership(), IpDropMembership(), IpMulticastTTL(), IpTOS(), IpTTL(), UdpSocket::IsBroadcast(), UdpSocket::IsMulticastLoop(), TcpSocket::OnConnectTimeout(), SctpSocket::OnConnectTimeout(), HttpClientSocket::OnData(), ResolvSocket::OnDelete(), ResolvSocket::OnDetached(), OnException(), HttpClientSocket::OnFirst(), ResolvSocket::OnLine(), UdpSocket::OnRead(), TcpSocket::OnRead(), SctpSocket::OnRead(), TcpSocket::OnResolved(), OnSocks4Connect(), TcpSocket::OnSocks4ConnectFailed(), OnSocks4ConnectFailed(), TcpSocket::OnSocks4Read(), OnSocks4Read(), TcpSocket::OnWrite(), SctpSocket::OnWrite(), UdpSocket::Open(), TcpSocket::Open(), SctpSocket::Open(), SctpSocket::PeelOff(), SctpSocket::RemoveAddress(), Resolve(), UdpSocket::SendBuf(), TcpSocket::SendBuf(), UdpSocket::SendToBuf(), Set(), UdpSocket::SetBroadcast(), StreamSocket::SetCallOnConnect(), SetClientRemoteAddress(), SetCloseAndDelete(), SetDetach(), HttpPutSocket::SetFile(), SetIpHdrincl(), SetIpMulticastTTL(), SetIpOptions(), SetIpTOS(), SetIpTTL(), UdpSocket::SetMulticastLoop(), SetMulticastLoop(), UdpSocket::SetMulticastTTL(), SetNonblocking(), StreamSocket::SetRetryClientConnect(), SetSoBroadcast(), SetSoDebug(), SetSoDontroute(), SetSoKeepalive(), SetSoLinger(), SetSoOobinline(), SetSoRcvbuf(), SetSoRcvlowat(), SetSoRcvtimeo(), SetSoReuseaddr(), SetSoSndbuf(), SetSoSndlowat(), SetSoSndtimeo(), TcpSocket::SetTcpNodelay(), SetTimeout(), SoAcceptconn(), SoError(), SoRcvbuf(), SoSndbuf(), SoType(), TcpSocket::SSLNegotiate(), TcpSocket::TryWrite(), HTTPSocket::url_this(), and ~Socket().

00293 {
00294 #ifdef ENABLE_DETACH
00295         if (IsDetached())
00296                 return *m_slave_handler;
00297 #endif
00298         return m_handler;
00299 }

ISocketHandler & Socket::MasterHandler (  )  const

Returns reference to sockethandler that owns the socket.

This one always returns the reference to the original sockethandler, even if the socket is detached.

Definition at line 302 of file Socket.cpp.

References m_handler.

00303 {
00304         return m_handler;
00305 }

void Socket::Init (  )  [virtual]

Called by ListenSocket after accept but before socket is added to handler.

CTcpSocket uses this to create its ICrypt member variable. The ICrypt member variable is created by a virtual method, therefore it can't be called directly from the CTcpSocket constructor. Also used to determine if incoming HTTP connection is normal (port 80) or ssl (port 443).

Reimplemented in HttpDebugSocket.

Definition at line 129 of file Socket.cpp.

Referenced by Ajp13Socket::ReceiveForwardRequest(), and Ajp13Socket::Respond().

00130 {
00131 }

SOCKET Socket::CreateSocket ( int  af,
int  type,
const std::string &  protocol = "" 
)

Create a socket file descriptor.

Parameters:
af Address family AF_INET / AF_INET6 / ...
type SOCK_STREAM / SOCK_DGRAM / ...
protocol "tcp" / "udp" / ...

Definition at line 195 of file Socket.cpp.

References Attach(), Errno, Handler(), INVALID_SOCKET, LOG_LEVEL_FATAL, ISocketHandler::LogError(), m_socket_protocol, m_socket_type, OnOptions(), SetCloseAndDelete(), and StrError.

Referenced by UdpSocket::Bind(), SctpSocket::Bind(), UdpSocket::CreateConnection(), UdpSocket::Open(), TcpSocket::Open(), SctpSocket::Open(), and UdpSocket::SendToBuf().

00196 {
00197         struct protoent *p = NULL;
00198         SOCKET s;
00199 
00200 #ifdef ENABLE_POOL
00201         m_socket_type = type;
00202         m_socket_protocol = protocol;
00203 #endif
00204         if (protocol.size())
00205         {
00206                 p = getprotobyname( protocol.c_str() );
00207                 if (!p)
00208                 {
00209                         Handler().LogError(this, "getprotobyname", Errno, StrError(Errno), LOG_LEVEL_FATAL);
00210                         SetCloseAndDelete();
00211 #ifdef ENABLE_EXCEPTIONS
00212                         throw Exception(std::string("getprotobyname() failed: ") + StrError(Errno));
00213 #endif
00214                         return INVALID_SOCKET;
00215                 }
00216         }
00217         int protno = p ? p -> p_proto : 0;
00218 
00219         s = socket(af, type, protno);
00220         if (s == INVALID_SOCKET)
00221         {
00222                 Handler().LogError(this, "socket", Errno, StrError(Errno), LOG_LEVEL_FATAL);
00223                 SetCloseAndDelete();
00224 #ifdef ENABLE_EXCEPTIONS
00225                 throw Exception(std::string("socket() failed: ") + StrError(Errno));
00226 #endif
00227                 return INVALID_SOCKET;
00228         }
00229         Attach(s);
00230         OnOptions(af, type, protno, s);
00231         Attach(INVALID_SOCKET);
00232         return s;
00233 }

void Socket::Attach ( SOCKET  s  ) 

Assign this socket a file descriptor created by a call to socket() or otherwise.

Definition at line 236 of file Socket.cpp.

References m_socket.

Referenced by UdpSocket::Bind(), SctpSocket::Bind(), CopyConnection(), UdpSocket::CreateConnection(), CreateSocket(), UdpSocket::Open(), TcpSocket::Open(), SctpSocket::Open(), SctpSocket::PeelOff(), and UdpSocket::SendToBuf().

00237 {
00238         m_socket = s;
00239 }

SOCKET Socket::GetSocket (  ) 

Return file descriptor assigned to this socket.

Definition at line 242 of file Socket.cpp.

References m_socket.

Referenced by SctpSocket::AddAddress(), SctpSocket::AddConnection(), UdpSocket::AddMulticastMembership(), UdpSocket::Bind(), SctpSocket::Bind(), TcpSocket::Close(), CopyConnection(), UdpSocket::CreateConnection(), UdpSocket::DropMulticastMembership(), SctpSocket::getladdrs(), UdpSocket::GetMulticastTTL(), SctpSocket::getpaddrs(), GetSockAddress(), GetSockIP4(), GetSockPort(), IpAddMembership(), IpDropMembership(), IpMulticastTTL(), IpTOS(), IpTTL(), UdpSocket::IsBroadcast(), UdpSocket::IsMulticastLoop(), UdpSocket::OnRead(), TcpSocket::OnRead(), SctpSocket::OnRead(), TcpSocket::OnSSLAccept(), TcpSocket::OnSSLConnect(), TcpSocket::OnWrite(), UdpSocket::Open(), SctpSocket::Open(), SctpSocket::PeelOff(), StreamSocket::Ready(), SctpSocket::RemoveAddress(), UdpSocket::SendBuf(), TcpSocket::SendBuf(), UdpSocket::SendToBuf(), UdpSocket::SetBroadcast(), StreamSocket::SetCallOnConnect(), SetIpHdrincl(), SetIpMulticastTTL(), SetIpOptions(), SetIpTOS(), SetIpTTL(), UdpSocket::SetMulticastLoop(), SetMulticastLoop(), UdpSocket::SetMulticastTTL(), StreamSocket::SetRetryClientConnect(), SetSoBroadcast(), SetSoDebug(), SetSoDontroute(), SetSoKeepalive(), SetSoLinger(), SetSoOobinline(), SetSoRcvbuf(), SetSoRcvlowat(), SetSoRcvtimeo(), SetSoReuseaddr(), SetSoSndbuf(), SetSoSndlowat(), SetSoSndtimeo(), TcpSocket::SetTcpNodelay(), SoAcceptconn(), SoError(), SoRcvbuf(), SoSndbuf(), SoType(), and TcpSocket::TryWrite().

00243 {
00244         return m_socket;
00245 }

int Socket::Close (  )  [virtual]