Code-style consistency improvement:

Apply clang-format-all.sh using the _clang-format file through all the cpp/.h files.
make sure not to apply it to certain serialization structures, since some parser expects the * as part of the name, instead of type.
This commit contains no other changes aside from adding and applying clang-format-all.sh
This commit is contained in:
erwincoumans
2018-09-23 14:17:31 -07:00
parent b73b05e9fb
commit ab8f16961e
1773 changed files with 1081087 additions and 474249 deletions

View File

@@ -53,77 +53,77 @@ CActiveSocket::CActiveSocket(CSocketType nType) : CSimpleSocket(nType)
//------------------------------------------------------------------------------
bool CActiveSocket::ConnectTCP(const char *pAddr, uint16 nPort)
{
bool bRetVal = false;
struct in_addr stIpAddress;
bool bRetVal = false;
struct in_addr stIpAddress;
//------------------------------------------------------------------
// Preconnection setup that must be preformed
//------------------------------------------------------------------
memset(&m_stServerSockaddr, 0, sizeof(m_stServerSockaddr));
m_stServerSockaddr.sin_family = AF_INET;
//------------------------------------------------------------------
// Preconnection setup that must be preformed
//------------------------------------------------------------------
memset(&m_stServerSockaddr, 0, sizeof(m_stServerSockaddr));
m_stServerSockaddr.sin_family = AF_INET;
if ((m_pHE = GETHOSTBYNAME(pAddr)) == NULL)
{
if ((m_pHE = GETHOSTBYNAME(pAddr)) == NULL)
{
#ifdef WIN32
TranslateSocketError();
TranslateSocketError();
#else
if (h_errno == HOST_NOT_FOUND)
{
SetSocketError(SocketInvalidAddress);
}
if (h_errno == HOST_NOT_FOUND)
{
SetSocketError(SocketInvalidAddress);
}
#endif
return bRetVal;
}
return bRetVal;
}
memcpy(&stIpAddress, m_pHE->h_addr_list[0], m_pHE->h_length);
m_stServerSockaddr.sin_addr.s_addr = stIpAddress.s_addr;
memcpy(&stIpAddress, m_pHE->h_addr_list[0], m_pHE->h_length);
m_stServerSockaddr.sin_addr.s_addr = stIpAddress.s_addr;
if ((int32)m_stServerSockaddr.sin_addr.s_addr == CSimpleSocket::SocketError)
{
TranslateSocketError();
return bRetVal;
}
if ((int32)m_stServerSockaddr.sin_addr.s_addr == CSimpleSocket::SocketError)
{
TranslateSocketError();
return bRetVal;
}
m_stServerSockaddr.sin_port = htons(nPort);
m_stServerSockaddr.sin_port = htons(nPort);
//------------------------------------------------------------------
// Connect to address "xxx.xxx.xxx.xxx" (IPv4) address only.
//
//------------------------------------------------------------------
m_timer.Initialize();
m_timer.SetStartTime();
//------------------------------------------------------------------
// Connect to address "xxx.xxx.xxx.xxx" (IPv4) address only.
//
//------------------------------------------------------------------
m_timer.Initialize();
m_timer.SetStartTime();
if (connect(m_socket, (struct sockaddr*)&m_stServerSockaddr, sizeof(m_stServerSockaddr)) ==
CSimpleSocket::SocketError)
{
//--------------------------------------------------------------
// Get error value this might be a non-blocking socket so we
// must first check.
//--------------------------------------------------------------
TranslateSocketError();
if (connect(m_socket, (struct sockaddr *)&m_stServerSockaddr, sizeof(m_stServerSockaddr)) ==
CSimpleSocket::SocketError)
{
//--------------------------------------------------------------
// Get error value this might be a non-blocking socket so we
// must first check.
//--------------------------------------------------------------
TranslateSocketError();
//--------------------------------------------------------------
// If the socket is non-blocking and the current socket error
// is SocketEinprogress or SocketEwouldblock then poll connection
// with select for designated timeout period.
// Linux returns EINPROGRESS and Windows returns WSAEWOULDBLOCK.
//--------------------------------------------------------------
if ((IsNonblocking()) &&
((GetSocketError() == CSimpleSocket::SocketEwouldblock) ||
(GetSocketError() == CSimpleSocket::SocketEinprogress)))
{
bRetVal = Select(GetConnectTimeoutSec(), GetConnectTimeoutUSec());
}
}
else
{
TranslateSocketError();
bRetVal = true;
}
//--------------------------------------------------------------
// If the socket is non-blocking and the current socket error
// is SocketEinprogress or SocketEwouldblock then poll connection
// with select for designated timeout period.
// Linux returns EINPROGRESS and Windows returns WSAEWOULDBLOCK.
//--------------------------------------------------------------
if ((IsNonblocking()) &&
((GetSocketError() == CSimpleSocket::SocketEwouldblock) ||
(GetSocketError() == CSimpleSocket::SocketEinprogress)))
{
bRetVal = Select(GetConnectTimeoutSec(), GetConnectTimeoutUSec());
}
}
else
{
TranslateSocketError();
bRetVal = true;
}
m_timer.SetEndTime();
m_timer.SetEndTime();
return bRetVal;
return bRetVal;
}
//------------------------------------------------------------------------------
@@ -133,56 +133,56 @@ bool CActiveSocket::ConnectTCP(const char *pAddr, uint16 nPort)
//------------------------------------------------------------------------------
bool CActiveSocket::ConnectUDP(const char *pAddr, uint16 nPort)
{
bool bRetVal = false;
struct in_addr stIpAddress;
bool bRetVal = false;
struct in_addr stIpAddress;
//------------------------------------------------------------------
// Pre-connection setup that must be preformed
//------------------------------------------------------------------
memset(&m_stServerSockaddr, 0, sizeof(m_stServerSockaddr));
m_stServerSockaddr.sin_family = AF_INET;
//------------------------------------------------------------------
// Pre-connection setup that must be preformed
//------------------------------------------------------------------
memset(&m_stServerSockaddr, 0, sizeof(m_stServerSockaddr));
m_stServerSockaddr.sin_family = AF_INET;
if ((m_pHE = GETHOSTBYNAME(pAddr)) == NULL)
{
if ((m_pHE = GETHOSTBYNAME(pAddr)) == NULL)
{
#ifdef WIN32
TranslateSocketError();
TranslateSocketError();
#else
if (h_errno == HOST_NOT_FOUND)
{
SetSocketError(SocketInvalidAddress);
}
if (h_errno == HOST_NOT_FOUND)
{
SetSocketError(SocketInvalidAddress);
}
#endif
return bRetVal;
}
return bRetVal;
}
memcpy(&stIpAddress, m_pHE->h_addr_list[0], m_pHE->h_length);
m_stServerSockaddr.sin_addr.s_addr = stIpAddress.s_addr;
memcpy(&stIpAddress, m_pHE->h_addr_list[0], m_pHE->h_length);
m_stServerSockaddr.sin_addr.s_addr = stIpAddress.s_addr;
if ((int32)m_stServerSockaddr.sin_addr.s_addr == CSimpleSocket::SocketError)
{
TranslateSocketError();
return bRetVal;
}
if ((int32)m_stServerSockaddr.sin_addr.s_addr == CSimpleSocket::SocketError)
{
TranslateSocketError();
return bRetVal;
}
m_stServerSockaddr.sin_port = htons(nPort);
m_stServerSockaddr.sin_port = htons(nPort);
//------------------------------------------------------------------
// Connect to address "xxx.xxx.xxx.xxx" (IPv4) address only.
//
//------------------------------------------------------------------
m_timer.Initialize();
m_timer.SetStartTime();
//------------------------------------------------------------------
// Connect to address "xxx.xxx.xxx.xxx" (IPv4) address only.
//
//------------------------------------------------------------------
m_timer.Initialize();
m_timer.SetStartTime();
if (connect(m_socket, (struct sockaddr*)&m_stServerSockaddr, sizeof(m_stServerSockaddr)) != CSimpleSocket::SocketError)
{
bRetVal = true;
}
if (connect(m_socket, (struct sockaddr *)&m_stServerSockaddr, sizeof(m_stServerSockaddr)) != CSimpleSocket::SocketError)
{
bRetVal = true;
}
TranslateSocketError();
TranslateSocketError();
m_timer.SetEndTime();
m_timer.SetEndTime();
return bRetVal;
return bRetVal;
}
//------------------------------------------------------------------------------
@@ -192,58 +192,57 @@ bool CActiveSocket::ConnectUDP(const char *pAddr, uint16 nPort)
//------------------------------------------------------------------------------
bool CActiveSocket::ConnectRAW(const char *pAddr, uint16 nPort)
{
bool bRetVal = false;
struct in_addr stIpAddress;
//------------------------------------------------------------------
// Pre-connection setup that must be preformed
//------------------------------------------------------------------
memset(&m_stServerSockaddr, 0, sizeof(m_stServerSockaddr));
m_stServerSockaddr.sin_family = AF_INET;
bool bRetVal = false;
struct in_addr stIpAddress;
//------------------------------------------------------------------
// Pre-connection setup that must be preformed
//------------------------------------------------------------------
memset(&m_stServerSockaddr, 0, sizeof(m_stServerSockaddr));
m_stServerSockaddr.sin_family = AF_INET;
if ((m_pHE = GETHOSTBYNAME(pAddr)) == NULL)
{
if ((m_pHE = GETHOSTBYNAME(pAddr)) == NULL)
{
#ifdef WIN32
TranslateSocketError();
TranslateSocketError();
#else
if (h_errno == HOST_NOT_FOUND)
{
SetSocketError(SocketInvalidAddress);
}
if (h_errno == HOST_NOT_FOUND)
{
SetSocketError(SocketInvalidAddress);
}
#endif
return bRetVal;
}
return bRetVal;
}
memcpy(&stIpAddress, m_pHE->h_addr_list[0], m_pHE->h_length);
m_stServerSockaddr.sin_addr.s_addr = stIpAddress.s_addr;
memcpy(&stIpAddress, m_pHE->h_addr_list[0], m_pHE->h_length);
m_stServerSockaddr.sin_addr.s_addr = stIpAddress.s_addr;
if ((int32)m_stServerSockaddr.sin_addr.s_addr == CSimpleSocket::SocketError)
{
TranslateSocketError();
return bRetVal;
}
if ((int32)m_stServerSockaddr.sin_addr.s_addr == CSimpleSocket::SocketError)
{
TranslateSocketError();
return bRetVal;
}
m_stServerSockaddr.sin_port = htons(nPort);
m_stServerSockaddr.sin_port = htons(nPort);
//------------------------------------------------------------------
// Connect to address "xxx.xxx.xxx.xxx" (IPv4) address only.
//
//------------------------------------------------------------------
m_timer.Initialize();
m_timer.SetStartTime();
//------------------------------------------------------------------
// Connect to address "xxx.xxx.xxx.xxx" (IPv4) address only.
//
//------------------------------------------------------------------
m_timer.Initialize();
m_timer.SetStartTime();
if (connect(m_socket, (struct sockaddr*)&m_stServerSockaddr, sizeof(m_stServerSockaddr)) != CSimpleSocket::SocketError)
{
bRetVal = true;
}
if (connect(m_socket, (struct sockaddr *)&m_stServerSockaddr, sizeof(m_stServerSockaddr)) != CSimpleSocket::SocketError)
{
bRetVal = true;
}
TranslateSocketError();
TranslateSocketError();
m_timer.SetEndTime();
m_timer.SetEndTime();
return bRetVal;
return bRetVal;
}
//------------------------------------------------------------------------------
//
// Open() - Create a connection to a specified address on a specified port
@@ -251,60 +250,60 @@ bool CActiveSocket::ConnectRAW(const char *pAddr, uint16 nPort)
//------------------------------------------------------------------------------
bool CActiveSocket::Open(const char *pAddr, uint16 nPort)
{
bool bRetVal = false;
bool bRetVal = false;
if (IsSocketValid() == false)
{
SetSocketError(CSimpleSocket::SocketInvalidSocket);
return bRetVal;
}
if (IsSocketValid() == false)
{
SetSocketError(CSimpleSocket::SocketInvalidSocket);
return bRetVal;
}
if (pAddr == NULL)
{
SetSocketError(CSimpleSocket::SocketInvalidAddress);
return bRetVal;
}
if (pAddr == NULL)
{
SetSocketError(CSimpleSocket::SocketInvalidAddress);
return bRetVal;
}
if (nPort == 0)
{
SetSocketError(CSimpleSocket::SocketInvalidPort);
return bRetVal;
}
if (nPort == 0)
{
SetSocketError(CSimpleSocket::SocketInvalidPort);
return bRetVal;
}
switch (m_nSocketType)
{
case CSimpleSocket::SocketTypeTcp :
{
bRetVal = ConnectTCP(pAddr, nPort);
break;
}
case CSimpleSocket::SocketTypeUdp :
{
bRetVal = ConnectUDP(pAddr, nPort);
break;
}
case CSimpleSocket::SocketTypeRaw :
break;
default:
break;
}
switch (m_nSocketType)
{
case CSimpleSocket::SocketTypeTcp:
{
bRetVal = ConnectTCP(pAddr, nPort);
break;
}
case CSimpleSocket::SocketTypeUdp:
{
bRetVal = ConnectUDP(pAddr, nPort);
break;
}
case CSimpleSocket::SocketTypeRaw:
break;
default:
break;
}
//--------------------------------------------------------------------------
// If successful then create a local copy of the address and port
//--------------------------------------------------------------------------
if (bRetVal)
{
socklen_t nSockLen = sizeof(struct sockaddr);
//--------------------------------------------------------------------------
// If successful then create a local copy of the address and port
//--------------------------------------------------------------------------
if (bRetVal)
{
socklen_t nSockLen = sizeof(struct sockaddr);
memset(&m_stServerSockaddr, 0, nSockLen);
getpeername(m_socket, (struct sockaddr *)&m_stServerSockaddr, &nSockLen);
memset(&m_stServerSockaddr, 0, nSockLen);
getpeername(m_socket, (struct sockaddr *)&m_stServerSockaddr, &nSockLen);
nSockLen = sizeof(struct sockaddr);
memset(&m_stClientSockaddr, 0, nSockLen);
getsockname(m_socket, (struct sockaddr *)&m_stClientSockaddr, &nSockLen);
nSockLen = sizeof(struct sockaddr);
memset(&m_stClientSockaddr, 0, nSockLen);
getsockname(m_socket, (struct sockaddr *)&m_stClientSockaddr, &nSockLen);
SetSocketError(SocketSuccess);
}
SetSocketError(SocketSuccess);
}
return bRetVal;
return bRetVal;
}

View File

@@ -51,41 +51,42 @@ class CPassiveSocket;
/// An active socket is used to create a socket which connects to a server.
/// This type of object would be used when an application needs to send/receive
/// data from a server.
class CActiveSocket : public CSimpleSocket {
class CActiveSocket : public CSimpleSocket
{
public:
friend class CPassiveSocket;
friend class CPassiveSocket;
CActiveSocket(CSocketType type = SocketTypeTcp);
virtual ~CActiveSocket() {
Close();
};
CActiveSocket(CSocketType type = SocketTypeTcp);
virtual ~CActiveSocket()
{
Close();
};
/// Established a connection to the address specified by pAddr.
/// Connection-based protocol sockets (CSocket::SocketTypeTcp) may
/// successfully call Open() only once, however; connectionless protocol
/// sockets (CSocket::SocketTypeUdp) may use Open() multiple times to
/// change their association.
/// @param pAddr specifies the destination address to connect.
/// @param nPort specifies the destination port.
/// @return true if successful connection made, otherwise false.
virtual bool Open(const char *pAddr, uint16 nPort);
/// Established a connection to the address specified by pAddr.
/// Connection-based protocol sockets (CSocket::SocketTypeTcp) may
/// successfully call Open() only once, however; connectionless protocol
/// sockets (CSocket::SocketTypeUdp) may use Open() multiple times to
/// change their association.
/// @param pAddr specifies the destination address to connect.
/// @param nPort specifies the destination port.
/// @return true if successful connection made, otherwise false.
virtual bool Open(const char *pAddr, uint16 nPort);
private:
/// Utility function used to create a TCP connection, called from Open().
/// @return true if successful connection made, otherwise false.
bool ConnectTCP(const char *pAddr, uint16 nPort);
/// Utility function used to create a TCP connection, called from Open().
/// @return true if successful connection made, otherwise false.
bool ConnectTCP(const char *pAddr, uint16 nPort);
/// Utility function used to create a UDP connection, called from Open().
/// @return true if successful connection made, otherwise false.
bool ConnectUDP(const char *pAddr, uint16 nPort);
/// Utility function used to create a UDP connection, called from Open().
/// @return true if successful connection made, otherwise false.
bool ConnectUDP(const char *pAddr, uint16 nPort);
/// Utility function used to create a RAW connection, called from Open().
/// @return true if successful connection made, otherwise false.
bool ConnectRAW(const char *pAddr, uint16 nPort);
/// Utility function used to create a RAW connection, called from Open().
/// @return true if successful connection made, otherwise false.
bool ConnectRAW(const char *pAddr, uint16 nPort);
private:
struct hostent *m_pHE;
struct hostent *m_pHE;
};
#endif /* __ACTIVESOCKET_H__ */

View File

@@ -57,91 +57,90 @@ extern "C"
/* */
/*---------------------------------------------------------------------------*/
#ifndef __WORDSIZE
/* Assume 32 */
#define __WORDSIZE 32
/* Assume 32 */
#define __WORDSIZE 32
#endif
#if defined(_LINUX) || defined(_DARWIN) || defined(_BSD)
typedef unsigned char uint8;
typedef char int8;
typedef unsigned short uint16;
typedef short int16;
typedef unsigned int uint32;
typedef int int32;
typedef int SOCKET;
typedef unsigned char uint8;
typedef char int8;
typedef unsigned short uint16;
typedef short int16;
typedef unsigned int uint32;
typedef int int32;
typedef int SOCKET;
#endif
#ifdef WIN32
struct iovec {
void *iov_base;
size_t iov_len;
};
struct iovec
{
void *iov_base;
size_t iov_len;
};
typedef unsigned char uint8;
typedef char int8;
typedef unsigned short uint16;
typedef short int16;
typedef unsigned int uint32;
typedef int int32;
typedef unsigned char uint8;
typedef char int8;
typedef unsigned short uint16;
typedef short int16;
typedef unsigned int uint32;
typedef int int32;
#endif
#ifdef WIN32
typedef int socklen_t;
typedef int socklen_t;
#endif
#if defined(WIN32)
typedef unsigned long long int uint64;
typedef long long int int64;
typedef unsigned long long int uint64;
typedef long long int int64;
#elif (__WORDSIZE == 32)
__extension__
typedef long long int int64;
__extension__
typedef unsigned long long int uint64;
__extension__ typedef long long int int64;
__extension__ typedef unsigned long long int uint64;
#elif (__WORDSIZE == 64)
typedef unsigned long int uint64;
typedef long int int64;
typedef unsigned long int uint64;
typedef long int int64;
#endif
#ifdef WIN32
#ifndef UINT8_MAX
#define UINT8_MAX (UCHAR_MAX)
#endif
#ifndef UINT16_MAX
#define UINT16_MAX (USHRT_MAX)
#endif
#ifndef UINT32_MAX
#define UINT32_MAX (ULONG_MAX)
#endif
#ifndef UINT8_MAX
#define UINT8_MAX (UCHAR_MAX)
#endif
#ifndef UINT16_MAX
#define UINT16_MAX (USHRT_MAX)
#endif
#ifndef UINT32_MAX
#define UINT32_MAX (ULONG_MAX)
#endif
#if __WORDSIZE == 64
#define SIZE_MAX (18446744073709551615UL)
#else
#ifndef SIZE_MAX
#define SIZE_MAX (4294967295U)
#endif
#endif
#if __WORDSIZE == 64
#define SIZE_MAX (18446744073709551615UL)
#else
#ifndef SIZE_MAX
#define SIZE_MAX (4294967295U)
#endif
#endif
#endif
#if defined(WIN32)
#define ssize_t size_t
#define ssize_t size_t
#endif
#ifndef TRUE
#define TRUE 1
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#define FALSE 0
#endif
#ifndef htonll
#ifdef _BIG_ENDIAN
#define htonll(x) (x)
#define ntohll(x) (x)
#define htonll(x) (x)
#define ntohll(x) (x)
#else
#define htonll(x) ((((uint64)htonl(x)) << 32) + htonl(x >> 32))
#define ntohll(x) ((((uint64)ntohl(x)) << 32) + ntohl(x >> 32))
#define htonll(x) ((((uint64)htonl(x)) << 32) + htonl(x >> 32))
#define ntohll(x) ((((uint64)ntohl(x)) << 32) + ntohl(x >> 32))
#endif
#endif
@@ -151,75 +150,73 @@ extern "C"
/* */
/*---------------------------------------------------------------------------*/
#ifdef WIN32
#define SHUT_RD 0
#define SHUT_WR 1
#define SHUT_RDWR 2
#define ACCEPT(a,b,c) accept(a,b,c)
#define CONNECT(a,b,c) connect(a,b,c)
#define CLOSE(a) closesocket(a)
#define READ(a,b,c) read(a,b,c)
#define RECV(a,b,c,d) recv(a, (char *)b, c, d)
#define RECVFROM(a,b,c,d,e,f) recvfrom(a, (char *)b, c, d, (sockaddr *)e, (int *)f)
#define RECV_FLAGS MSG_WAITALL
#define SELECT(a,b,c,d,e) select((int32)a,b,c,d,e)
#define SEND(a,b,c,d) send(a, (const char *)b, (int)c, d)
#define SENDTO(a,b,c,d,e,f) sendto(a, (const char *)b, (int)c, d, e, f)
#define SEND_FLAGS 0
#define SENDFILE(a,b,c,d) sendfile(a, b, c, d)
#define SET_SOCKET_ERROR(x,y) errno=y
#define SOCKET_ERROR_INTERUPT EINTR
#define SOCKET_ERROR_TIMEDOUT EAGAIN
#define WRITE(a,b,c) write(a,b,c)
#define WRITEV(a,b,c) Writev(b, c)
#define GETSOCKOPT(a,b,c,d,e) getsockopt(a,b,c,(char *)d, (int *)e)
#define SETSOCKOPT(a,b,c,d,e) setsockopt(a,b,c,(char *)d, (int)e)
#define GETHOSTBYNAME(a) gethostbyname(a)
#define SHUT_RD 0
#define SHUT_WR 1
#define SHUT_RDWR 2
#define ACCEPT(a, b, c) accept(a, b, c)
#define CONNECT(a, b, c) connect(a, b, c)
#define CLOSE(a) closesocket(a)
#define READ(a, b, c) read(a, b, c)
#define RECV(a, b, c, d) recv(a, (char *)b, c, d)
#define RECVFROM(a, b, c, d, e, f) recvfrom(a, (char *)b, c, d, (sockaddr *)e, (int *)f)
#define RECV_FLAGS MSG_WAITALL
#define SELECT(a, b, c, d, e) select((int32)a, b, c, d, e)
#define SEND(a, b, c, d) send(a, (const char *)b, (int)c, d)
#define SENDTO(a, b, c, d, e, f) sendto(a, (const char *)b, (int)c, d, e, f)
#define SEND_FLAGS 0
#define SENDFILE(a, b, c, d) sendfile(a, b, c, d)
#define SET_SOCKET_ERROR(x, y) errno = y
#define SOCKET_ERROR_INTERUPT EINTR
#define SOCKET_ERROR_TIMEDOUT EAGAIN
#define WRITE(a, b, c) write(a, b, c)
#define WRITEV(a, b, c) Writev(b, c)
#define GETSOCKOPT(a, b, c, d, e) getsockopt(a, b, c, (char *)d, (int *)e)
#define SETSOCKOPT(a, b, c, d, e) setsockopt(a, b, c, (char *)d, (int)e)
#define GETHOSTBYNAME(a) gethostbyname(a)
#endif
#if defined(_LINUX) || defined(_DARWIN) || defined(_BSD)
#define ACCEPT(a,b,c) accept(a,b,c)
#define CONNECT(a,b,c) connect(a,b,c)
#define CLOSE(a) close(a)
#define READ(a,b,c) read(a,b,c)
#define RECV(a,b,c,d) recv(a, (void *)b, c, d)
#define RECVFROM(a,b,c,d,e,f) recvfrom(a, (char *)b, c, d, (sockaddr *)e, f)
#define RECV_FLAGS MSG_WAITALL
#define SELECT(a,b,c,d,e) select(a,b,c,d,e)
#define SEND(a,b,c,d) send(a, (const int8 *)b, c, d)
#define SENDTO(a,b,c,d,e,f) sendto(a, (const int8 *)b, c, d, e, f)
#define SEND_FLAGS 0
#define SENDFILE(a,b,c,d) sendfile(a, b, c, d)
#define SET_SOCKET_ERROR(x,y) errno=y
#define SOCKET_ERROR_INTERUPT EINTR
#define SOCKET_ERROR_TIMEDOUT EAGAIN
#define WRITE(a,b,c) write(a,b,c)
#define WRITEV(a,b,c) writev(a, b, c)
#define GETSOCKOPT(a,b,c,d,e) getsockopt((int)a,(int)b,(int)c,(void *)d,(socklen_t *)e)
#define SETSOCKOPT(a,b,c,d,e) setsockopt((int)a,(int)b,(int)c,(const void *)d,(int)e)
#define GETHOSTBYNAME(a) gethostbyname(a)
#define ACCEPT(a, b, c) accept(a, b, c)
#define CONNECT(a, b, c) connect(a, b, c)
#define CLOSE(a) close(a)
#define READ(a, b, c) read(a, b, c)
#define RECV(a, b, c, d) recv(a, (void *)b, c, d)
#define RECVFROM(a, b, c, d, e, f) recvfrom(a, (char *)b, c, d, (sockaddr *)e, f)
#define RECV_FLAGS MSG_WAITALL
#define SELECT(a, b, c, d, e) select(a, b, c, d, e)
#define SEND(a, b, c, d) send(a, (const int8 *)b, c, d)
#define SENDTO(a, b, c, d, e, f) sendto(a, (const int8 *)b, c, d, e, f)
#define SEND_FLAGS 0
#define SENDFILE(a, b, c, d) sendfile(a, b, c, d)
#define SET_SOCKET_ERROR(x, y) errno = y
#define SOCKET_ERROR_INTERUPT EINTR
#define SOCKET_ERROR_TIMEDOUT EAGAIN
#define WRITE(a, b, c) write(a, b, c)
#define WRITEV(a, b, c) writev(a, b, c)
#define GETSOCKOPT(a, b, c, d, e) getsockopt((int)a, (int)b, (int)c, (void *)d, (socklen_t *)e)
#define SETSOCKOPT(a, b, c, d, e) setsockopt((int)a, (int)b, (int)c, (const void *)d, (int)e)
#define GETHOSTBYNAME(a) gethostbyname(a)
#endif
/*---------------------------------------------------------------------------*/
/* */
/* File Macros */
/* */
/*---------------------------------------------------------------------------*/
#define STRUCT_STAT struct stat
#define LSTAT(x,y) lstat(x,y)
#define FILE_HANDLE FILE *
#define CLEARERR(x) clearerr(x)
#define FCLOSE(x) fclose(x)
#define FEOF(x) feof(x)
#define FERROR(x) ferror(x)
#define FFLUSH(x) fflush(x)
#define FILENO(s) fileno(s)
#define FOPEN(x,y) fopen(x, y)
//#define FREAD(a,b,c,d) fread(a, b, c, d)
#define FSTAT(s, st) fstat(FILENO(s), st)
//#define FWRITE(a,b,c,d) fwrite(a, b, c, d)
#define STAT_BLK_SIZE(x) ((x).st_blksize)
#define STRUCT_STAT struct stat
#define LSTAT(x, y) lstat(x, y)
#define FILE_HANDLE FILE *
#define CLEARERR(x) clearerr(x)
#define FCLOSE(x) fclose(x)
#define FEOF(x) feof(x)
#define FERROR(x) ferror(x)
#define FFLUSH(x) fflush(x)
#define FILENO(s) fileno(s)
#define FOPEN(x, y) fopen(x, y)
//#define FREAD(a,b,c,d) fread(a, b, c, d)
#define FSTAT(s, st) fstat(FILENO(s), st)
//#define FWRITE(a,b,c,d) fwrite(a, b, c, d)
#define STAT_BLK_SIZE(x) ((x).st_blksize)
/*---------------------------------------------------------------------------*/
/* */
@@ -227,27 +224,27 @@ extern "C"
/* */
/*---------------------------------------------------------------------------*/
#if defined(WIN32)
#define GET_CLOCK_COUNT(x) QueryPerformanceCounter((LARGE_INTEGER *)x)
#define GET_CLOCK_COUNT(x) QueryPerformanceCounter((LARGE_INTEGER *)x)
#else
#define GET_CLOCK_COUNT(x) gettimeofday(x, NULL)
#define GET_CLOCK_COUNT(x) gettimeofday(x, NULL)
#endif
#if defined(WIN32)
#define STRTOULL(x) _atoi64(x)
#define STRTOULL(x) _atoi64(x)
#else
#define STRTOULL(x) strtoull(x, NULL, 10)
#define STRTOULL(x) strtoull(x, NULL, 10)
#endif
#if defined(WIN32)
#define SNPRINTF _snprintf
#define PRINTF printf
#define VPRINTF vprintf
#define FPRINTF fprintf
#define SNPRINTF _snprintf
#define PRINTF printf
#define VPRINTF vprintf
#define FPRINTF fprintf
#else
#define SNPRINTF snprintf
#define PRINTF printf
#define VPRINTF vprintf
#define FPRINTF fprintf
#define SNPRINTF snprintf
#define PRINTF printf
#define VPRINTF vprintf
#define FPRINTF fprintf
#endif
#ifdef __cplusplus

View File

@@ -42,89 +42,85 @@
*----------------------------------------------------------------------------*/
#include "PassiveSocket.h"
CPassiveSocket::CPassiveSocket(CSocketType nType) : CSimpleSocket(nType)
{
}
bool CPassiveSocket::BindMulticast(const char *pInterface, const char *pGroup, uint16 nPort)
{
bool bRetVal = false;
bool bRetVal = false;
#ifdef WIN32
ULONG inAddr;
ULONG inAddr;
#else
int32 nReuse;
in_addr_t inAddr;
int32 nReuse;
in_addr_t inAddr;
nReuse = IPTOS_LOWDELAY;
nReuse = IPTOS_LOWDELAY;
#endif
//--------------------------------------------------------------------------
// Set the following socket option SO_REUSEADDR. This will allow the file
// descriptor to be reused immediately after the socket is closed instead
// of setting in a TIMED_WAIT state.
//--------------------------------------------------------------------------
memset(&m_stMulticastGroup,0,sizeof(m_stMulticastGroup));
m_stMulticastGroup.sin_family = AF_INET;
m_stMulticastGroup.sin_port = htons(nPort);
//--------------------------------------------------------------------------
// Set the following socket option SO_REUSEADDR. This will allow the file
// descriptor to be reused immediately after the socket is closed instead
// of setting in a TIMED_WAIT state.
//--------------------------------------------------------------------------
memset(&m_stMulticastGroup, 0, sizeof(m_stMulticastGroup));
m_stMulticastGroup.sin_family = AF_INET;
m_stMulticastGroup.sin_port = htons(nPort);
//--------------------------------------------------------------------------
// If no IP Address (interface ethn) is supplied, or the loop back is
// specified then bind to any interface, else bind to specified interface.
//--------------------------------------------------------------------------
if ((pInterface == NULL) || (!strlen(pInterface)))
{
m_stMulticastGroup.sin_addr.s_addr = htonl(INADDR_ANY);
}
else
{
if ((inAddr = inet_addr(pInterface)) != INADDR_NONE)
{
m_stMulticastGroup.sin_addr.s_addr = inAddr;
}
}
//--------------------------------------------------------------------------
// If no IP Address (interface ethn) is supplied, or the loop back is
// specified then bind to any interface, else bind to specified interface.
//--------------------------------------------------------------------------
if ((pInterface == NULL) || (!strlen(pInterface)))
{
m_stMulticastGroup.sin_addr.s_addr = htonl(INADDR_ANY);
}
else
{
if ((inAddr = inet_addr(pInterface)) != INADDR_NONE)
{
m_stMulticastGroup.sin_addr.s_addr = inAddr;
}
}
//--------------------------------------------------------------------------
// Bind to the specified port
//--------------------------------------------------------------------------
if (bind(m_socket, (struct sockaddr *)&m_stMulticastGroup, sizeof(m_stMulticastGroup)) == 0)
{
//----------------------------------------------------------------------
// Join the multicast group
//----------------------------------------------------------------------
m_stMulticastRequest.imr_multiaddr.s_addr = inet_addr(pGroup);
m_stMulticastRequest.imr_interface.s_addr = m_stMulticastGroup.sin_addr.s_addr;
//--------------------------------------------------------------------------
// Bind to the specified port
//--------------------------------------------------------------------------
if (bind(m_socket, (struct sockaddr *)&m_stMulticastGroup, sizeof(m_stMulticastGroup)) == 0)
{
//----------------------------------------------------------------------
// Join the multicast group
//----------------------------------------------------------------------
m_stMulticastRequest.imr_multiaddr.s_addr = inet_addr(pGroup);
m_stMulticastRequest.imr_interface.s_addr = m_stMulticastGroup.sin_addr.s_addr;
if (SETSOCKOPT(m_socket, IPPROTO_IP, IP_ADD_MEMBERSHIP,
(void *)&m_stMulticastRequest,
sizeof(m_stMulticastRequest)) == CSimpleSocket::SocketSuccess)
{
bRetVal = true;
}
if (SETSOCKOPT(m_socket, IPPROTO_IP, IP_ADD_MEMBERSHIP,
(void *)&m_stMulticastRequest,
sizeof(m_stMulticastRequest)) == CSimpleSocket::SocketSuccess)
{
bRetVal = true;
}
m_timer.SetEndTime();
}
m_timer.SetEndTime();
}
m_timer.Initialize();
m_timer.SetStartTime();
m_timer.Initialize();
m_timer.SetStartTime();
//--------------------------------------------------------------------------
// If there was a socket error then close the socket to clean out the
// connection in the backlog.
//--------------------------------------------------------------------------
TranslateSocketError();
//--------------------------------------------------------------------------
// If there was a socket error then close the socket to clean out the
// connection in the backlog.
//--------------------------------------------------------------------------
TranslateSocketError();
if (bRetVal == false)
{
Close();
}
if (bRetVal == false)
{
Close();
}
return bRetVal;
return bRetVal;
}
//------------------------------------------------------------------------------
//
// Listen() -
@@ -132,84 +128,83 @@ bool CPassiveSocket::BindMulticast(const char *pInterface, const char *pGroup, u
//------------------------------------------------------------------------------
bool CPassiveSocket::Listen(const char *pAddr, uint16 nPort, int32 nConnectionBacklog)
{
bool bRetVal = false;
bool bRetVal = false;
#ifdef WIN32
ULONG inAddr;
ULONG inAddr;
#else
int32 nReuse;
in_addr_t inAddr;
int32 nReuse;
in_addr_t inAddr;
nReuse = IPTOS_LOWDELAY;
nReuse = IPTOS_LOWDELAY;
#endif
//--------------------------------------------------------------------------
// Set the following socket option SO_REUSEADDR. This will allow the file
// descriptor to be reused immediately after the socket is closed instead
// of setting in a TIMED_WAIT state.
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
// Set the following socket option SO_REUSEADDR. This will allow the file
// descriptor to be reused immediately after the socket is closed instead
// of setting in a TIMED_WAIT state.
//--------------------------------------------------------------------------
#ifdef _LINUX
SETSOCKOPT(m_socket, SOL_SOCKET, SO_REUSEADDR, (char*)&nReuse, sizeof(int32));
SETSOCKOPT(m_socket, IPPROTO_TCP, IP_TOS, &nReuse, sizeof(int32));
SETSOCKOPT(m_socket, SOL_SOCKET, SO_REUSEADDR, (char *)&nReuse, sizeof(int32));
SETSOCKOPT(m_socket, IPPROTO_TCP, IP_TOS, &nReuse, sizeof(int32));
#endif
memset(&m_stServerSockaddr,0,sizeof(m_stServerSockaddr));
m_stServerSockaddr.sin_family = AF_INET;
m_stServerSockaddr.sin_port = htons(nPort);
memset(&m_stServerSockaddr, 0, sizeof(m_stServerSockaddr));
m_stServerSockaddr.sin_family = AF_INET;
m_stServerSockaddr.sin_port = htons(nPort);
//--------------------------------------------------------------------------
// If no IP Address (interface ethn) is supplied, or the loop back is
// specified then bind to any interface, else bind to specified interface.
//--------------------------------------------------------------------------
if ((pAddr == NULL) || (!strlen(pAddr)))
{
m_stServerSockaddr.sin_addr.s_addr = htonl(INADDR_ANY);
}
else
{
if ((inAddr = inet_addr(pAddr)) != INADDR_NONE)
{
m_stServerSockaddr.sin_addr.s_addr = inAddr;
}
}
//--------------------------------------------------------------------------
// If no IP Address (interface ethn) is supplied, or the loop back is
// specified then bind to any interface, else bind to specified interface.
//--------------------------------------------------------------------------
if ((pAddr == NULL) || (!strlen(pAddr)))
{
m_stServerSockaddr.sin_addr.s_addr = htonl(INADDR_ANY);
}
else
{
if ((inAddr = inet_addr(pAddr)) != INADDR_NONE)
{
m_stServerSockaddr.sin_addr.s_addr = inAddr;
}
}
m_timer.Initialize();
m_timer.SetStartTime();
m_timer.Initialize();
m_timer.SetStartTime();
//--------------------------------------------------------------------------
// Bind to the specified port
//--------------------------------------------------------------------------
if (bind(m_socket, (struct sockaddr *)&m_stServerSockaddr, sizeof(m_stServerSockaddr)) != CSimpleSocket::SocketError)
{
if (m_nSocketType == CSimpleSocket::SocketTypeTcp)
{
if (listen(m_socket, nConnectionBacklog) != CSimpleSocket::SocketError)
{
bRetVal = true;
}
}
else
{
bRetVal = true;
}
}
//--------------------------------------------------------------------------
// Bind to the specified port
//--------------------------------------------------------------------------
if (bind(m_socket, (struct sockaddr *)&m_stServerSockaddr, sizeof(m_stServerSockaddr)) != CSimpleSocket::SocketError)
{
if (m_nSocketType == CSimpleSocket::SocketTypeTcp)
{
if (listen(m_socket, nConnectionBacklog) != CSimpleSocket::SocketError)
{
bRetVal = true;
}
}
else
{
bRetVal = true;
}
}
m_timer.SetEndTime();
m_timer.SetEndTime();
//--------------------------------------------------------------------------
// If there was a socket error then close the socket to clean out the
// connection in the backlog.
//--------------------------------------------------------------------------
TranslateSocketError();
//--------------------------------------------------------------------------
// If there was a socket error then close the socket to clean out the
// connection in the backlog.
//--------------------------------------------------------------------------
TranslateSocketError();
if (bRetVal == false)
{
Close();
}
if (bRetVal == false)
{
Close();
}
return bRetVal;
return bRetVal;
}
//------------------------------------------------------------------------------
//
// Accept() -
@@ -217,73 +212,72 @@ bool CPassiveSocket::Listen(const char *pAddr, uint16 nPort, int32 nConnectionBa
//------------------------------------------------------------------------------
CActiveSocket *CPassiveSocket::Accept()
{
uint32 nSockLen;
CActiveSocket *pClientSocket = NULL;
SOCKET socket = CSimpleSocket::SocketError;
uint32 nSockLen;
CActiveSocket *pClientSocket = NULL;
SOCKET socket = CSimpleSocket::SocketError;
if (m_nSocketType != CSimpleSocket::SocketTypeTcp)
{
SetSocketError(CSimpleSocket::SocketProtocolError);
return pClientSocket;
}
if (m_nSocketType != CSimpleSocket::SocketTypeTcp)
{
SetSocketError(CSimpleSocket::SocketProtocolError);
return pClientSocket;
}
pClientSocket = new CActiveSocket();
pClientSocket = new CActiveSocket();
//--------------------------------------------------------------------------
// Wait for incoming connection.
//--------------------------------------------------------------------------
if (pClientSocket != NULL)
{
CSocketError socketErrno = SocketSuccess;
//--------------------------------------------------------------------------
// Wait for incoming connection.
//--------------------------------------------------------------------------
if (pClientSocket != NULL)
{
CSocketError socketErrno = SocketSuccess;
m_timer.Initialize();
m_timer.SetStartTime();
m_timer.Initialize();
m_timer.SetStartTime();
nSockLen = sizeof(m_stClientSockaddr);
nSockLen = sizeof(m_stClientSockaddr);
do
{
errno = 0;
socket = accept(m_socket, (struct sockaddr *)&m_stClientSockaddr, (socklen_t *)&nSockLen);
do
{
errno = 0;
socket = accept(m_socket, (struct sockaddr *)&m_stClientSockaddr, (socklen_t *)&nSockLen);
if (socket != -1)
{
pClientSocket->SetSocketHandle(socket);
pClientSocket->TranslateSocketError();
socketErrno = pClientSocket->GetSocketError();
socklen_t nSockLen = sizeof(struct sockaddr);
if (socket != -1)
{
pClientSocket->SetSocketHandle(socket);
pClientSocket->TranslateSocketError();
socketErrno = pClientSocket->GetSocketError();
socklen_t nSockLen = sizeof(struct sockaddr);
//-------------------------------------------------------------
// Store client and server IP and port information for this
// connection.
//-------------------------------------------------------------
getpeername(m_socket, (struct sockaddr *)&pClientSocket->m_stClientSockaddr, &nSockLen);
memcpy((void *)&pClientSocket->m_stClientSockaddr, (void *)&m_stClientSockaddr, nSockLen);
//-------------------------------------------------------------
// Store client and server IP and port information for this
// connection.
//-------------------------------------------------------------
getpeername(m_socket, (struct sockaddr *)&pClientSocket->m_stClientSockaddr, &nSockLen);
memcpy((void *)&pClientSocket->m_stClientSockaddr, (void *)&m_stClientSockaddr, nSockLen);
memset(&pClientSocket->m_stServerSockaddr, 0, nSockLen);
getsockname(m_socket, (struct sockaddr *)&pClientSocket->m_stServerSockaddr, &nSockLen);
}
else
{
TranslateSocketError();
socketErrno = GetSocketError();
}
memset(&pClientSocket->m_stServerSockaddr, 0, nSockLen);
getsockname(m_socket, (struct sockaddr *)&pClientSocket->m_stServerSockaddr, &nSockLen);
}
else
{
TranslateSocketError();
socketErrno = GetSocketError();
}
} while (socketErrno == CSimpleSocket::SocketInterrupted);
} while (socketErrno == CSimpleSocket::SocketInterrupted);
m_timer.SetEndTime();
m_timer.SetEndTime();
if (socketErrno != CSimpleSocket::SocketSuccess)
{
delete pClientSocket;
pClientSocket = NULL;
}
}
if (socketErrno != CSimpleSocket::SocketSuccess)
{
delete pClientSocket;
pClientSocket = NULL;
}
}
return pClientSocket;
return pClientSocket;
}
//------------------------------------------------------------------------------
//
// Send() - Send data on a valid socket
@@ -291,41 +285,41 @@ CActiveSocket *CPassiveSocket::Accept()
//------------------------------------------------------------------------------
int32 CPassiveSocket::Send(const uint8 *pBuf, size_t bytesToSend)
{
SetSocketError(SocketSuccess);
m_nBytesSent = 0;
SetSocketError(SocketSuccess);
m_nBytesSent = 0;
switch(m_nSocketType)
{
case CSimpleSocket::SocketTypeUdp:
{
if (IsSocketValid())
{
if ((bytesToSend > 0) && (pBuf != NULL))
{
m_timer.Initialize();
m_timer.SetStartTime();
switch (m_nSocketType)
{
case CSimpleSocket::SocketTypeUdp:
{
if (IsSocketValid())
{
if ((bytesToSend > 0) && (pBuf != NULL))
{
m_timer.Initialize();
m_timer.SetStartTime();
m_nBytesSent = SENDTO(m_socket, pBuf, bytesToSend, 0,
(const sockaddr *)&m_stClientSockaddr,
sizeof(m_stClientSockaddr));
m_nBytesSent = SENDTO(m_socket, pBuf, bytesToSend, 0,
(const sockaddr *)&m_stClientSockaddr,
sizeof(m_stClientSockaddr));
m_timer.SetEndTime();
m_timer.SetEndTime();
if (m_nBytesSent == CSimpleSocket::SocketError)
{
TranslateSocketError();
}
}
}
break;
}
case CSimpleSocket::SocketTypeTcp:
CSimpleSocket::Send(pBuf, bytesToSend);
break;
default:
SetSocketError(SocketProtocolError);
break;
}
if (m_nBytesSent == CSimpleSocket::SocketError)
{
TranslateSocketError();
}
}
}
break;
}
case CSimpleSocket::SocketTypeTcp:
CSimpleSocket::Send(pBuf, bytesToSend);
break;
default:
SetSocketError(SocketProtocolError);
break;
}
return m_nBytesSent;
return m_nBytesSent;
}

View File

@@ -52,68 +52,69 @@
/// in a similar fashion. The big difference is that the method
/// CPassiveSocket::Accept should not be called on the latter two socket
/// types.
class CPassiveSocket : public CSimpleSocket {
class CPassiveSocket : public CSimpleSocket
{
public:
CPassiveSocket(CSocketType type = SocketTypeTcp);
virtual ~CPassiveSocket() {
Close();
};
CPassiveSocket(CSocketType type = SocketTypeTcp);
virtual ~CPassiveSocket()
{
Close();
};
/// Extracts the first connection request on the queue of pending
/// connections and creates a newly connected socket. Used with
/// CSocketType CSimpleSocket::SocketTypeTcp. It is the responsibility of
/// the caller to delete the returned object when finished.
/// @return if successful a pointer to a newly created CActiveSocket object
/// will be returned and the internal error condition of the CPassiveSocket
/// object will be CPassiveSocket::SocketSuccess. If an error condition was encountered
/// the NULL will be returned and one of the following error conditions will be set:
/// CPassiveSocket::SocketEwouldblock, CPassiveSocket::SocketInvalidSocket,
/// CPassiveSocket::SocketConnectionAborted, CPassiveSocket::SocketInterrupted
/// CPassiveSocket::SocketProtocolError, CPassiveSocket::SocketFirewallError
virtual CActiveSocket *Accept(void);
/// Extracts the first connection request on the queue of pending
/// connections and creates a newly connected socket. Used with
/// CSocketType CSimpleSocket::SocketTypeTcp. It is the responsibility of
/// the caller to delete the returned object when finished.
/// @return if successful a pointer to a newly created CActiveSocket object
/// will be returned and the internal error condition of the CPassiveSocket
/// object will be CPassiveSocket::SocketSuccess. If an error condition was encountered
/// the NULL will be returned and one of the following error conditions will be set:
/// CPassiveSocket::SocketEwouldblock, CPassiveSocket::SocketInvalidSocket,
/// CPassiveSocket::SocketConnectionAborted, CPassiveSocket::SocketInterrupted
/// CPassiveSocket::SocketProtocolError, CPassiveSocket::SocketFirewallError
virtual CActiveSocket *Accept(void);
/// Bind to a multicast group on a specified interface, multicast group, and port
///
/// @param pInterface - interface on which to bind.
/// @param pGroup - multicast group address to bind.
/// @param nPort - port on which multicast
/// @return true if able to bind to interface and multicast group.
/// If not successful, the false is returned and one of the following error
/// condiitions will be set: CPassiveSocket::SocketAddressInUse, CPassiveSocket::SocketProtocolError,
/// CPassiveSocket::SocketInvalidSocket. The following socket errors are for Linux/Unix
/// derived systems only: CPassiveSocket::SocketInvalidSocketBuffer
bool BindMulticast(const char *pInterface, const char *pGroup, uint16 nPort);
/// Bind to a multicast group on a specified interface, multicast group, and port
///
/// @param pInterface - interface on which to bind.
/// @param pGroup - multicast group address to bind.
/// @param nPort - port on which multicast
/// @return true if able to bind to interface and multicast group.
/// If not successful, the false is returned and one of the following error
/// condiitions will be set: CPassiveSocket::SocketAddressInUse, CPassiveSocket::SocketProtocolError,
/// CPassiveSocket::SocketInvalidSocket. The following socket errors are for Linux/Unix
/// derived systems only: CPassiveSocket::SocketInvalidSocketBuffer
bool BindMulticast(const char *pInterface, const char *pGroup, uint16 nPort);
/// Create a listening socket at local ip address 'x.x.x.x' or 'localhost'
/// if pAddr is NULL on port nPort.
///
/// @param pAddr specifies the IP address on which to listen.
/// @param nPort specifies the port on which to listen.
/// @param nConnectionBacklog specifies connection queue backlog (default 30,000)
/// @return true if a listening socket was created.
/// If not successful, the false is returned and one of the following error
/// conditions will be set: CPassiveSocket::SocketAddressInUse, CPassiveSocket::SocketProtocolError,
/// CPassiveSocket::SocketInvalidSocket. The following socket errors are for Linux/Unix
/// derived systems only: CPassiveSocket::SocketInvalidSocketBuffer
virtual bool Listen(const char *pAddr, uint16 nPort, int32 nConnectionBacklog = 30000);
/// Create a listening socket at local ip address 'x.x.x.x' or 'localhost'
/// if pAddr is NULL on port nPort.
///
/// @param pAddr specifies the IP address on which to listen.
/// @param nPort specifies the port on which to listen.
/// @param nConnectionBacklog specifies connection queue backlog (default 30,000)
/// @return true if a listening socket was created.
/// If not successful, the false is returned and one of the following error
/// conditions will be set: CPassiveSocket::SocketAddressInUse, CPassiveSocket::SocketProtocolError,
/// CPassiveSocket::SocketInvalidSocket. The following socket errors are for Linux/Unix
/// derived systems only: CPassiveSocket::SocketInvalidSocketBuffer
virtual bool Listen(const char *pAddr, uint16 nPort, int32 nConnectionBacklog = 30000);
/// Attempts to send a block of data on an established connection.
/// @param pBuf block of data to be sent.
/// @param bytesToSend size of data block to be sent.
/// @return number of bytes actually sent, return of zero means the
/// connection has been shutdown on the other side, and a return of -1
/// means that an error has occurred. If an error was signaled then one
/// of the following error codes will be set: CPassiveSocket::SocketInvalidSocket,
/// CPassiveSocket::SocketEwouldblock, SimpleSocket::SocketConnectionReset,
/// CPassiveSocket::SocketInvalidSocketBuffer, CPassiveSocket::SocketInterrupted,
/// CPassiveSocket::SocketProtocolError, CPassiveSocket::SocketNotconnected
/// <br>\b Note: This function is used only for a socket of type
/// CSimpleSocket::SocketTypeUdp
virtual int32 Send(const uint8 *pBuf, size_t bytesToSend);
/// Attempts to send a block of data on an established connection.
/// @param pBuf block of data to be sent.
/// @param bytesToSend size of data block to be sent.
/// @return number of bytes actually sent, return of zero means the
/// connection has been shutdown on the other side, and a return of -1
/// means that an error has occurred. If an error was signaled then one
/// of the following error codes will be set: CPassiveSocket::SocketInvalidSocket,
/// CPassiveSocket::SocketEwouldblock, SimpleSocket::SocketConnectionReset,
/// CPassiveSocket::SocketInvalidSocketBuffer, CPassiveSocket::SocketInterrupted,
/// CPassiveSocket::SocketProtocolError, CPassiveSocket::SocketNotconnected
/// <br>\b Note: This function is used only for a socket of type
/// CSimpleSocket::SocketTypeUdp
virtual int32 Send(const uint8 *pBuf, size_t bytesToSend);
private:
struct ip_mreq m_stMulticastRequest; /// group address for multicast
struct ip_mreq m_stMulticastRequest; /// group address for multicast
};
#endif // __PASSIVESOCKET_H__
#endif // __PASSIVESOCKET_H__

File diff suppressed because it is too large Load Diff

View File

@@ -49,7 +49,7 @@
#include <stdarg.h>
#include <errno.h>
#if defined(_LINUX) || defined (_DARWIN) || defined(_BSD)
#if defined(_LINUX) || defined(_DARWIN) || defined(_BSD)
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
@@ -66,7 +66,7 @@
#ifdef _DARWIN
#include <net/if.h>
#endif
#if defined(_LINUX) || defined (_DARWIN) || defined(_BSD)
#if defined(_LINUX) || defined(_DARWIN) || defined(_BSD)
#include <sys/time.h>
#include <sys/uio.h>
#include <unistd.h>
@@ -78,7 +78,7 @@
#include <winsock2.h>
#include <ws2tcpip.h>
#define IPTOS_LOWDELAY 0x10
#define IPTOS_LOWDELAY 0x10
#endif
#include "Host.h"
@@ -88,7 +88,7 @@
// General class macro definitions and typedefs
//-----------------------------------------------------------------------------
#ifndef INVALID_SOCKET
#define INVALID_SOCKET ~(0)
#define INVALID_SOCKET ~(0)
#endif
#define SOCKET_SENDFILE_BLOCKSIZE 8192
@@ -99,321 +99,337 @@
/// - Socket types
/// -# CActiveSocket Class
/// -# CPassiveSocket Class
class CSimpleSocket {
class CSimpleSocket
{
public:
/// Defines the three possible states for shuting down a socket.
typedef enum
{
Receives = SHUT_RD, ///< Shutdown passive socket.
Sends = SHUT_WR, ///< Shutdown active socket.
Both = SHUT_RDWR ///< Shutdown both active and passive sockets.
} CShutdownMode;
/// Defines the three possible states for shuting down a socket.
typedef enum
{
Receives = SHUT_RD, ///< Shutdown passive socket.
Sends = SHUT_WR, ///< Shutdown active socket.
Both = SHUT_RDWR ///< Shutdown both active and passive sockets.
} CShutdownMode;
/// Defines the socket types defined by CSimpleSocket class.
typedef enum
{
SocketTypeInvalid, ///< Invalid socket type.
SocketTypeTcp, ///< Defines socket as TCP socket.
SocketTypeUdp, ///< Defines socket as UDP socket.
SocketTypeTcp6, ///< Defines socket as IPv6 TCP socket.
SocketTypeUdp6, ///< Defines socket as IPv6 UDP socket.
SocketTypeRaw ///< Provides raw network protocol access.
} CSocketType;
/// Defines the socket types defined by CSimpleSocket class.
typedef enum
{
SocketTypeInvalid, ///< Invalid socket type.
SocketTypeTcp, ///< Defines socket as TCP socket.
SocketTypeUdp, ///< Defines socket as UDP socket.
SocketTypeTcp6, ///< Defines socket as IPv6 TCP socket.
SocketTypeUdp6, ///< Defines socket as IPv6 UDP socket.
SocketTypeRaw ///< Provides raw network protocol access.
} CSocketType;
/// Defines all error codes handled by the CSimpleSocket class.
typedef enum
{
SocketError = -1, ///< Generic socket error translates to error below.
SocketSuccess = 0, ///< No socket error.
SocketInvalidSocket, ///< Invalid socket handle.
SocketInvalidAddress, ///< Invalid destination address specified.
SocketInvalidPort, ///< Invalid destination port specified.
SocketConnectionRefused, ///< No server is listening at remote address.
SocketTimedout, ///< Timed out while attempting operation.
SocketEwouldblock, ///< Operation would block if socket were blocking.
SocketNotconnected, ///< Currently not connected.
SocketEinprogress, ///< Socket is non-blocking and the connection cannot be completed immediately
SocketInterrupted, ///< Call was interrupted by a signal that was caught before a valid connection arrived.
SocketConnectionAborted, ///< The connection has been aborted.
SocketProtocolError, ///< Invalid protocol for operation.
SocketFirewallError, ///< Firewall rules forbid connection.
SocketInvalidSocketBuffer, ///< The receive buffer point outside the process's address space.
SocketConnectionReset, ///< Connection was forcibly closed by the remote host.
SocketAddressInUse, ///< Address already in use.
SocketInvalidPointer, ///< Pointer type supplied as argument is invalid.
SocketEunknown ///< Unknown error please report to mark@carrierlabs.com
} CSocketError;
/// Defines all error codes handled by the CSimpleSocket class.
typedef enum
{
SocketError = -1, ///< Generic socket error translates to error below.
SocketSuccess = 0, ///< No socket error.
SocketInvalidSocket, ///< Invalid socket handle.
SocketInvalidAddress, ///< Invalid destination address specified.
SocketInvalidPort, ///< Invalid destination port specified.
SocketConnectionRefused, ///< No server is listening at remote address.
SocketTimedout, ///< Timed out while attempting operation.
SocketEwouldblock, ///< Operation would block if socket were blocking.
SocketNotconnected, ///< Currently not connected.
SocketEinprogress, ///< Socket is non-blocking and the connection cannot be completed immediately
SocketInterrupted, ///< Call was interrupted by a signal that was caught before a valid connection arrived.
SocketConnectionAborted, ///< The connection has been aborted.
SocketProtocolError, ///< Invalid protocol for operation.
SocketFirewallError, ///< Firewall rules forbid connection.
SocketInvalidSocketBuffer, ///< The receive buffer point outside the process's address space.
SocketConnectionReset, ///< Connection was forcibly closed by the remote host.
SocketAddressInUse, ///< Address already in use.
SocketInvalidPointer, ///< Pointer type supplied as argument is invalid.
SocketEunknown ///< Unknown error please report to mark@carrierlabs.com
} CSocketError;
public:
CSimpleSocket(CSocketType type = SocketTypeTcp);
CSimpleSocket(CSimpleSocket &socket);
CSimpleSocket(CSocketType type = SocketTypeTcp);
CSimpleSocket(CSimpleSocket &socket);
virtual ~CSimpleSocket()
{
if (m_pBuffer != NULL)
{
delete [] m_pBuffer;
m_pBuffer = NULL;
}
};
virtual ~CSimpleSocket()
{
if (m_pBuffer != NULL)
{
delete[] m_pBuffer;
m_pBuffer = NULL;
}
};
/// Initialize instance of CSocket. This method MUST be called before an
/// object can be used. Errors : CSocket::SocketProtocolError,
/// CSocket::SocketInvalidSocket,
/// @return true if properly initialized.
virtual bool Initialize(void);
/// Initialize instance of CSocket. This method MUST be called before an
/// object can be used. Errors : CSocket::SocketProtocolError,
/// CSocket::SocketInvalidSocket,
/// @return true if properly initialized.
virtual bool Initialize(void);
/// Close socket
/// @return true if successfully closed otherwise returns false.
virtual bool Close(void);
/// Close socket
/// @return true if successfully closed otherwise returns false.
virtual bool Close(void);
/// Shutdown shut down socket send and receive operations
/// CShutdownMode::Receives - Disables further receive operations.
/// CShutdownMode::Sends - Disables further send operations.
/// CShutdownBoth:: - Disables further send and receive operations.
/// @param nShutdown specifies the type of shutdown.
/// @return true if successfully shutdown otherwise returns false.
virtual bool Shutdown(CShutdownMode nShutdown);
/// Shutdown shut down socket send and receive operations
/// CShutdownMode::Receives - Disables further receive operations.
/// CShutdownMode::Sends - Disables further send operations.
/// CShutdownBoth:: - Disables further send and receive operations.
/// @param nShutdown specifies the type of shutdown.
/// @return true if successfully shutdown otherwise returns false.
virtual bool Shutdown(CShutdownMode nShutdown);
/// Examine the socket descriptor sets currently owned by the instance of
/// the socket class (the readfds, writefds, and errorfds parameters) to
/// see whether some of their descriptors are ready for reading, are ready
/// for writing, or have an exceptional condition pending, respectively.
/// Block until an event happens on the specified file descriptors.
/// @return true if socket has data ready, or false if not ready or timed out.
virtual bool Select(void) {
return Select(0,0);
};
/// Examine the socket descriptor sets currently owned by the instance of
/// the socket class (the readfds, writefds, and errorfds parameters) to
/// see whether some of their descriptors are ready for reading, are ready
/// for writing, or have an exceptional condition pending, respectively.
/// Block until an event happens on the specified file descriptors.
/// @return true if socket has data ready, or false if not ready or timed out.
virtual bool Select(void)
{
return Select(0, 0);
};
/// Examine the socket descriptor sets currently owned by the instance of
/// the socket class (the readfds, writefds, and errorfds parameters) to
/// see whether some of their descriptors are ready for reading, are ready
/// for writing, or have an exceptional condition pending, respectively.
/// @param nTimeoutSec timeout in seconds for select.
/// @param nTimeoutUSec timeout in micro seconds for select.
/// @return true if socket has data ready, or false if not ready or timed out.
virtual bool Select(int32 nTimeoutSec, int32 nTimeoutUSec);
/// Examine the socket descriptor sets currently owned by the instance of
/// the socket class (the readfds, writefds, and errorfds parameters) to
/// see whether some of their descriptors are ready for reading, are ready
/// for writing, or have an exceptional condition pending, respectively.
/// @param nTimeoutSec timeout in seconds for select.
/// @param nTimeoutUSec timeout in micro seconds for select.
/// @return true if socket has data ready, or false if not ready or timed out.
virtual bool Select(int32 nTimeoutSec, int32 nTimeoutUSec);
/// Does the current instance of the socket object contain a valid socket
/// descriptor.
/// @return true if the socket object contains a valid socket descriptor.
virtual bool IsSocketValid(void) {
return (m_socket != SocketError);
};
/// Does the current instance of the socket object contain a valid socket
/// descriptor.
/// @return true if the socket object contains a valid socket descriptor.
virtual bool IsSocketValid(void)
{
return (m_socket != SocketError);
};
/// Provides a standard error code for cross platform development by
/// mapping the operating system error to an error defined by the CSocket
/// class.
void TranslateSocketError(void);
/// Provides a standard error code for cross platform development by
/// mapping the operating system error to an error defined by the CSocket
/// class.
void TranslateSocketError(void);
/// Returns a human-readable description of the given error code
/// or the last error code of a socket
static const char *DescribeError(CSocketError err);
inline const char *DescribeError() {
return DescribeError(m_socketErrno);
};
/// Returns a human-readable description of the given error code
/// or the last error code of a socket
static const char *DescribeError(CSocketError err);
inline const char *DescribeError()
{
return DescribeError(m_socketErrno);
};
/// Attempts to receive a block of data on an established connection.
/// @param nMaxBytes maximum number of bytes to receive.
/// @param pBuffer, memory where to receive the data,
/// NULL receives to internal buffer returned with GetData()
/// Non-NULL receives directly there, but GetData() will return WRONG ptr!
/// @return number of bytes actually received.
/// @return of zero means the connection has been shutdown on the other side.
/// @return of -1 means that an error has occurred.
virtual int32 Receive(int32 nMaxBytes = 1, uint8 * pBuffer = 0);
/// Attempts to receive a block of data on an established connection.
/// @param nMaxBytes maximum number of bytes to receive.
/// @param pBuffer, memory where to receive the data,
/// NULL receives to internal buffer returned with GetData()
/// Non-NULL receives directly there, but GetData() will return WRONG ptr!
/// @return number of bytes actually received.
/// @return of zero means the connection has been shutdown on the other side.
/// @return of -1 means that an error has occurred.
virtual int32 Receive(int32 nMaxBytes = 1, uint8 *pBuffer = 0);
/// Attempts to send a block of data on an established connection.
/// @param pBuf block of data to be sent.
/// @param bytesToSend size of data block to be sent.
/// @return number of bytes actually sent.
/// @return of zero means the connection has been shutdown on the other side.
/// @return of -1 means that an error has occurred.
virtual int32 Send(const uint8 *pBuf, size_t bytesToSend);
/// Attempts to send a block of data on an established connection.
/// @param pBuf block of data to be sent.
/// @param bytesToSend size of data block to be sent.
/// @return number of bytes actually sent.
/// @return of zero means the connection has been shutdown on the other side.
/// @return of -1 means that an error has occurred.
virtual int32 Send(const uint8 *pBuf, size_t bytesToSend);
/// Attempts to send at most nNumItem blocks described by sendVector
/// to the socket descriptor associated with the socket object.
/// @param sendVector pointer to an array of iovec structures
/// @param nNumItems number of items in the vector to process
/// <br>\b NOTE: Buffers are processed in the order specified.
/// @return number of bytes actually sent, return of zero means the
/// connection has been shutdown on the other side, and a return of -1
/// means that an error has occurred.
virtual int32 Send(const struct iovec *sendVector, int32 nNumItems);
/// Attempts to send at most nNumItem blocks described by sendVector
/// to the socket descriptor associated with the socket object.
/// @param sendVector pointer to an array of iovec structures
/// @param nNumItems number of items in the vector to process
/// <br>\b NOTE: Buffers are processed in the order specified.
/// @return number of bytes actually sent, return of zero means the
/// connection has been shutdown on the other side, and a return of -1
/// means that an error has occurred.
virtual int32 Send(const struct iovec *sendVector, int32 nNumItems);
/// Copies data between one file descriptor and another.
/// On some systems this copying is done within the kernel, and thus is
/// more efficient than the combination of CSimpleSocket::Send and
/// CSimpleSocket::Receive, which would require transferring data to and
/// from user space.
/// <br>\b Note: This is available on all implementations, but the kernel
/// implementation is only available on Unix type systems.
/// @param nOutFd descriptor opened for writing.
/// @param nInFd descriptor opened for reading.
/// @param pOffset from which to start reading data from input file.
/// @param nCount number of bytes to copy between file descriptors.
/// @return number of bytes written to the out socket descriptor.
virtual int32 SendFile(int32 nOutFd, int32 nInFd, off_t *pOffset, int32 nCount);
/// Copies data between one file descriptor and another.
/// On some systems this copying is done within the kernel, and thus is
/// more efficient than the combination of CSimpleSocket::Send and
/// CSimpleSocket::Receive, which would require transferring data to and
/// from user space.
/// <br>\b Note: This is available on all implementations, but the kernel
/// implementation is only available on Unix type systems.
/// @param nOutFd descriptor opened for writing.
/// @param nInFd descriptor opened for reading.
/// @param pOffset from which to start reading data from input file.
/// @param nCount number of bytes to copy between file descriptors.
/// @return number of bytes written to the out socket descriptor.
virtual int32 SendFile(int32 nOutFd, int32 nInFd, off_t *pOffset, int32 nCount);
/// Returns blocking/non-blocking state of socket.
/// @return true if the socket is non-blocking, else return false.
bool IsNonblocking(void) {
return (m_bIsBlocking == false);
};
/// Returns blocking/non-blocking state of socket.
/// @return true if the socket is non-blocking, else return false.
bool IsNonblocking(void)
{
return (m_bIsBlocking == false);
};
/// Set the socket to blocking.
/// @return true if successful set to blocking, else return false;
bool SetBlocking(void);
/// Set the socket to blocking.
/// @return true if successful set to blocking, else return false;
bool SetBlocking(void);
/// Set the socket as non-blocking.
/// @return true if successful set to non-blocking, else return false;
bool SetNonblocking(void);
/// Set the socket as non-blocking.
/// @return true if successful set to non-blocking, else return false;
bool SetNonblocking(void);
/// Get a pointer to internal receive buffer. The user MUST not free this
/// pointer when finished. This memory is managed internally by the CSocket
/// class.
/// @return pointer to data if valid, else returns NULL.
uint8 *GetData(void) {
return m_pBuffer;
};
/// Get a pointer to internal receive buffer. The user MUST not free this
/// pointer when finished. This memory is managed internally by the CSocket
/// class.
/// @return pointer to data if valid, else returns NULL.
uint8 *GetData(void)
{
return m_pBuffer;
};
/// Returns the number of bytes received on the last call to
/// CSocket::Receive().
/// @return number of bytes received.
int32 GetBytesReceived(void) {
return m_nBytesReceived;
};
/// Returns the number of bytes received on the last call to
/// CSocket::Receive().
/// @return number of bytes received.
int32 GetBytesReceived(void)
{
return m_nBytesReceived;
};
/// Returns the number of bytes sent on the last call to
/// CSocket::Send().
/// @return number of bytes sent.
int32 GetBytesSent(void) {
return m_nBytesSent;
};
/// Returns the number of bytes sent on the last call to
/// CSocket::Send().
/// @return number of bytes sent.
int32 GetBytesSent(void)
{
return m_nBytesSent;
};
/// Controls the actions taken when CSimpleSocket::Close is executed on a
/// socket object that has unsent data. The default value for this option
/// is \b off.
/// - Following are the three possible scenarios.
/// -# \b bEnable is false, CSimpleSocket::Close returns immediately, but
/// any unset data is transmitted (after CSimpleSocket::Close returns)
/// -# \b bEnable is true and \b nTime is zero, CSimpleSocket::Close return
/// immediately and any unsent data is discarded.
/// -# \b bEnable is true and \b nTime is nonzero, CSimpleSocket::Close does
/// not return until all unsent data is transmitted (or the connection is
/// Closed by the remote system).
/// <br><p>
/// @param bEnable true to enable option false to disable option.
/// @param nTime time in seconds to linger.
/// @return true if option successfully set
bool SetOptionLinger(bool bEnable, uint16 nTime);
/// Controls the actions taken when CSimpleSocket::Close is executed on a
/// socket object that has unsent data. The default value for this option
/// is \b off.
/// - Following are the three possible scenarios.
/// -# \b bEnable is false, CSimpleSocket::Close returns immediately, but
/// any unset data is transmitted (after CSimpleSocket::Close returns)
/// -# \b bEnable is true and \b nTime is zero, CSimpleSocket::Close return
/// immediately and any unsent data is discarded.
/// -# \b bEnable is true and \b nTime is nonzero, CSimpleSocket::Close does
/// not return until all unsent data is transmitted (or the connection is
/// Closed by the remote system).
/// <br><p>
/// @param bEnable true to enable option false to disable option.
/// @param nTime time in seconds to linger.
/// @return true if option successfully set
bool SetOptionLinger(bool bEnable, uint16 nTime);
/// Tells the kernel that even if this port is busy (in the TIME_WAIT state),
/// go ahead and reuse it anyway. If it is busy, but with another state,
/// you will still get an address already in use error.
/// @return true if option successfully set
bool SetOptionReuseAddr();
/// Tells the kernel that even if this port is busy (in the TIME_WAIT state),
/// go ahead and reuse it anyway. If it is busy, but with another state,
/// you will still get an address already in use error.
/// @return true if option successfully set
bool SetOptionReuseAddr();
/// Gets the timeout value that specifies the maximum number of seconds a
/// call to CSimpleSocket::Open waits until it completes.
/// @return the length of time in seconds
int32 GetConnectTimeoutSec(void) {
return m_stConnectTimeout.tv_sec;
};
/// Gets the timeout value that specifies the maximum number of seconds a
/// call to CSimpleSocket::Open waits until it completes.
/// @return the length of time in seconds
int32 GetConnectTimeoutSec(void)
{
return m_stConnectTimeout.tv_sec;
};
/// Gets the timeout value that specifies the maximum number of microseconds
/// a call to CSimpleSocket::Open waits until it completes.
/// @return the length of time in microseconds
int32 GetConnectTimeoutUSec(void) {
return m_stConnectTimeout.tv_usec;
};
/// Gets the timeout value that specifies the maximum number of microseconds
/// a call to CSimpleSocket::Open waits until it completes.
/// @return the length of time in microseconds
int32 GetConnectTimeoutUSec(void)
{
return m_stConnectTimeout.tv_usec;
};
/// Sets the timeout value that specifies the maximum amount of time a call
/// to CSimpleSocket::Receive waits until it completes. Use the method
/// CSimpleSocket::SetReceiveTimeout to specify the number of seconds to wait.
/// If a call to CSimpleSocket::Receive has blocked for the specified length of
/// time without receiving additional data, it returns with a partial count
/// or CSimpleSocket::GetSocketError set to CSimpleSocket::SocketEwouldblock if no data
/// were received.
/// @param nConnectTimeoutSec of timeout in seconds.
/// @param nConnectTimeoutUsec of timeout in microseconds.
/// @return true if socket connection timeout was successfully set.
void SetConnectTimeout(int32 nConnectTimeoutSec, int32 nConnectTimeoutUsec = 0)
{
m_stConnectTimeout.tv_sec = nConnectTimeoutSec;
m_stConnectTimeout.tv_usec = nConnectTimeoutUsec;
};
/// Sets the timeout value that specifies the maximum amount of time a call
/// to CSimpleSocket::Receive waits until it completes. Use the method
/// CSimpleSocket::SetReceiveTimeout to specify the number of seconds to wait.
/// If a call to CSimpleSocket::Receive has blocked for the specified length of
/// time without receiving additional data, it returns with a partial count
/// or CSimpleSocket::GetSocketError set to CSimpleSocket::SocketEwouldblock if no data
/// were received.
/// @param nConnectTimeoutSec of timeout in seconds.
/// @param nConnectTimeoutUsec of timeout in microseconds.
/// @return true if socket connection timeout was successfully set.
void SetConnectTimeout(int32 nConnectTimeoutSec, int32 nConnectTimeoutUsec = 0)
{
m_stConnectTimeout.tv_sec = nConnectTimeoutSec;
m_stConnectTimeout.tv_usec = nConnectTimeoutUsec;
};
/// Gets the timeout value that specifies the maximum number of seconds a
/// a call to CSimpleSocket::Receive waits until it completes.
/// @return the length of time in seconds
int32 GetReceiveTimeoutSec(void) {
return m_stRecvTimeout.tv_sec;
};
/// Gets the timeout value that specifies the maximum number of seconds a
/// a call to CSimpleSocket::Receive waits until it completes.
/// @return the length of time in seconds
int32 GetReceiveTimeoutSec(void)
{
return m_stRecvTimeout.tv_sec;
};
/// Gets the timeout value that specifies the maximum number of microseconds
/// a call to CSimpleSocket::Receive waits until it completes.
/// @return the length of time in microseconds
int32 GetReceiveTimeoutUSec(void) {
return m_stRecvTimeout.tv_usec;
};
/// Gets the timeout value that specifies the maximum number of microseconds
/// a call to CSimpleSocket::Receive waits until it completes.
/// @return the length of time in microseconds
int32 GetReceiveTimeoutUSec(void)
{
return m_stRecvTimeout.tv_usec;
};
/// Sets the timeout value that specifies the maximum amount of time a call
/// to CSimpleSocket::Receive waits until it completes. Use the method
/// CSimpleSocket::SetReceiveTimeout to specify the number of seconds to wait.
/// If a call to CSimpleSocket::Receive has blocked for the specified length of
/// time without receiving additional data, it returns with a partial count
/// or CSimpleSocket::GetSocketError set to CSimpleSocket::SocketEwouldblock if no data
/// were received.
/// @param nRecvTimeoutSec of timeout in seconds.
/// @param nRecvTimeoutUsec of timeout in microseconds.
/// @return true if socket timeout was successfully set.
bool SetReceiveTimeout(int32 nRecvTimeoutSec, int32 nRecvTimeoutUsec = 0);
/// Sets the timeout value that specifies the maximum amount of time a call
/// to CSimpleSocket::Receive waits until it completes. Use the method
/// CSimpleSocket::SetReceiveTimeout to specify the number of seconds to wait.
/// If a call to CSimpleSocket::Receive has blocked for the specified length of
/// time without receiving additional data, it returns with a partial count
/// or CSimpleSocket::GetSocketError set to CSimpleSocket::SocketEwouldblock if no data
/// were received.
/// @param nRecvTimeoutSec of timeout in seconds.
/// @param nRecvTimeoutUsec of timeout in microseconds.
/// @return true if socket timeout was successfully set.
bool SetReceiveTimeout(int32 nRecvTimeoutSec, int32 nRecvTimeoutUsec = 0);
/// Enable/disable multicast for a socket. This options is only valid for
/// socket descriptors of type CSimpleSocket::SocketTypeUdp.
/// @return true if multicast was enabled or false if socket type is not
/// CSimpleSocket::SocketTypeUdp and the error will be set to
/// CSimpleSocket::SocketProtocolError
bool SetMulticast(bool bEnable, uint8 multicastTTL = 1);
/// Enable/disable multicast for a socket. This options is only valid for
/// socket descriptors of type CSimpleSocket::SocketTypeUdp.
/// @return true if multicast was enabled or false if socket type is not
/// CSimpleSocket::SocketTypeUdp and the error will be set to
/// CSimpleSocket::SocketProtocolError
bool SetMulticast(bool bEnable, uint8 multicastTTL = 1);
/// Return true if socket is multicast or false is socket is unicast
/// @return true if multicast is enabled
bool GetMulticast() {
return m_bIsMulticast;
};
/// Return true if socket is multicast or false is socket is unicast
/// @return true if multicast is enabled
bool GetMulticast()
{
return m_bIsMulticast;
};
/// Bind socket to a specific interface when using multicast.
/// @return true if successfully bound to interface
bool BindInterface(const char *pInterface);
/// Bind socket to a specific interface when using multicast.
/// @return true if successfully bound to interface
bool BindInterface(const char *pInterface);
/// Gets the timeout value that specifies the maximum number of seconds a
/// a call to CSimpleSocket::Send waits until it completes.
/// @return the length of time in seconds
int32 GetSendTimeoutSec(void) {
return m_stSendTimeout.tv_sec;
};
/// Gets the timeout value that specifies the maximum number of seconds a
/// a call to CSimpleSocket::Send waits until it completes.
/// @return the length of time in seconds
int32 GetSendTimeoutSec(void)
{
return m_stSendTimeout.tv_sec;
};
/// Gets the timeout value that specifies the maximum number of microseconds
/// a call to CSimpleSocket::Send waits until it completes.
/// @return the length of time in microseconds
int32 GetSendTimeoutUSec(void) {
return m_stSendTimeout.tv_usec;
};
/// Gets the timeout value that specifies the maximum number of microseconds
/// a call to CSimpleSocket::Send waits until it completes.
/// @return the length of time in microseconds
int32 GetSendTimeoutUSec(void)
{
return m_stSendTimeout.tv_usec;
};
/// Gets the timeout value that specifies the maximum amount of time a call
/// to CSimpleSocket::Send waits until it completes.
/// @return the length of time in seconds
bool SetSendTimeout(int32 nSendTimeoutSec, int32 nSendTimeoutUsec = 0);
/// Gets the timeout value that specifies the maximum amount of time a call
/// to CSimpleSocket::Send waits until it completes.
/// @return the length of time in seconds
bool SetSendTimeout(int32 nSendTimeoutSec, int32 nSendTimeoutUsec = 0);
/// Returns the last error that occured for the instace of the CSimpleSocket
/// instance. This method should be called immediately to retrieve the
/// error code for the failing mehtod call.
/// @return last error that occured.
CSocketError GetSocketError(void) {
return m_socketErrno;
};
/*
/// Returns the last error that occured for the instace of the CSimpleSocket
/// instance. This method should be called immediately to retrieve the
/// error code for the failing mehtod call.
/// @return last error that occured.
CSocketError GetSocketError(void)
{
return m_socketErrno;
};
/*
CSocketError GetSocketError(void) {
CSocketError err = m_socketErrno;
m_socketErrno = SocketSuccess;
@@ -422,170 +438,180 @@ public:
};
*/
/// Get the total time the of the last operation in milliseconds.
/// @return number of milliseconds of last operation.
uint32 GetTotalTimeMs() {
return m_timer.GetMilliSeconds();
};
/// Get the total time the of the last operation in milliseconds.
/// @return number of milliseconds of last operation.
uint32 GetTotalTimeMs()
{
return m_timer.GetMilliSeconds();
};
/// Get the total time the of the last operation in microseconds.
/// @return number of microseconds or last operation.
uint32 GetTotalTimeUsec() {
return m_timer.GetMicroSeconds();
};
/// Get the total time the of the last operation in microseconds.
/// @return number of microseconds or last operation.
uint32 GetTotalTimeUsec()
{
return m_timer.GetMicroSeconds();
};
/// Return Differentiated Services Code Point (DSCP) value currently set on the socket object.
/// @return DSCP for current socket object.
/// <br><br> \b NOTE: Windows special notes http://support.microsoft.com/kb/248611.
int GetSocketDscp(void);
/// Return Differentiated Services Code Point (DSCP) value currently set on the socket object.
/// @return DSCP for current socket object.
/// <br><br> \b NOTE: Windows special notes http://support.microsoft.com/kb/248611.
int GetSocketDscp(void);
/// Set Differentiated Services Code Point (DSCP) for socket object.
/// @param nDscp value of TOS setting which will be converted to DSCP
/// @return true if DSCP value was properly set
/// <br><br> \b NOTE: Windows special notes http://support.microsoft.com/kb/248611.
bool SetSocketDscp(int nDscp);
/// Set Differentiated Services Code Point (DSCP) for socket object.
/// @param nDscp value of TOS setting which will be converted to DSCP
/// @return true if DSCP value was properly set
/// <br><br> \b NOTE: Windows special notes http://support.microsoft.com/kb/248611.
bool SetSocketDscp(int nDscp);
/// Return socket descriptor
/// @return socket descriptor which is a signed 32 bit integer.
SOCKET GetSocketDescriptor() {
return m_socket;
};
/// Return socket descriptor
/// @return socket descriptor which is a signed 32 bit integer.
SOCKET GetSocketDescriptor()
{
return m_socket;
};
/// Return socket descriptor
/// @return socket descriptor which is a signed 32 bit integer.
CSocketType GetSocketType() {
return m_nSocketType;
};
/// Return socket descriptor
/// @return socket descriptor which is a signed 32 bit integer.
CSocketType GetSocketType()
{
return m_nSocketType;
};
/// Returns clients Internet host address as a string in standard numbers-and-dots notation.
/// @return NULL if invalid
const char *GetClientAddr() {
return inet_ntoa(m_stClientSockaddr.sin_addr);
};
/// Returns clients Internet host address as a string in standard numbers-and-dots notation.
/// @return NULL if invalid
const char *GetClientAddr()
{
return inet_ntoa(m_stClientSockaddr.sin_addr);
};
/// Returns the port number on which the client is connected.
/// @return client port number.
uint16 GetClientPort() {
return m_stClientSockaddr.sin_port;
};
/// Returns the port number on which the client is connected.
/// @return client port number.
uint16 GetClientPort()
{
return m_stClientSockaddr.sin_port;
};
/// Returns server Internet host address as a string in standard numbers-and-dots notation.
/// @return NULL if invalid
const char *GetServerAddr() {
return inet_ntoa(m_stServerSockaddr.sin_addr);
};
/// Returns server Internet host address as a string in standard numbers-and-dots notation.
/// @return NULL if invalid
const char *GetServerAddr()
{
return inet_ntoa(m_stServerSockaddr.sin_addr);
};
/// Returns the port number on which the server is connected.
/// @return server port number.
uint16 GetServerPort() {
return ntohs(m_stServerSockaddr.sin_port);
};
/// Returns the port number on which the server is connected.
/// @return server port number.
uint16 GetServerPort()
{
return ntohs(m_stServerSockaddr.sin_port);
};
/// Get the TCP receive buffer window size for the current socket object.
/// <br><br>\b NOTE: Linux will set the receive buffer to twice the value passed.
/// @return zero on failure else the number of bytes of the TCP receive buffer window size if successful.
uint32 GetReceiveWindowSize() {
return GetWindowSize(SO_RCVBUF);
};
/// Get the TCP receive buffer window size for the current socket object.
/// <br><br>\b NOTE: Linux will set the receive buffer to twice the value passed.
/// @return zero on failure else the number of bytes of the TCP receive buffer window size if successful.
uint32 GetReceiveWindowSize()
{
return GetWindowSize(SO_RCVBUF);
};
/// Get the TCP send buffer window size for the current socket object.
/// <br><br>\b NOTE: Linux will set the send buffer to twice the value passed.
/// @return zero on failure else the number of bytes of the TCP receive buffer window size if successful.
uint32 GetSendWindowSize() {
return GetWindowSize(SO_SNDBUF);
};
/// Get the TCP send buffer window size for the current socket object.
/// <br><br>\b NOTE: Linux will set the send buffer to twice the value passed.
/// @return zero on failure else the number of bytes of the TCP receive buffer window size if successful.
uint32 GetSendWindowSize()
{
return GetWindowSize(SO_SNDBUF);
};
/// Set the TCP receive buffer window size for the current socket object.
/// <br><br>\b NOTE: Linux will set the receive buffer to twice the value passed.
/// @return zero on failure else the number of bytes of the TCP send buffer window size if successful.
uint32 SetReceiveWindowSize(uint32 nWindowSize) {
return SetWindowSize(SO_RCVBUF, nWindowSize);
};
/// Set the TCP receive buffer window size for the current socket object.
/// <br><br>\b NOTE: Linux will set the receive buffer to twice the value passed.
/// @return zero on failure else the number of bytes of the TCP send buffer window size if successful.
uint32 SetReceiveWindowSize(uint32 nWindowSize)
{
return SetWindowSize(SO_RCVBUF, nWindowSize);
};
/// Set the TCP send buffer window size for the current socket object.
/// <br><br>\b NOTE: Linux will set the send buffer to twice the value passed.
/// @return zero on failure else the number of bytes of the TCP send buffer window size if successful.
uint32 SetSendWindowSize(uint32 nWindowSize) {
return SetWindowSize(SO_SNDBUF, nWindowSize);
};
/// Set the TCP send buffer window size for the current socket object.
/// <br><br>\b NOTE: Linux will set the send buffer to twice the value passed.
/// @return zero on failure else the number of bytes of the TCP send buffer window size if successful.
uint32 SetSendWindowSize(uint32 nWindowSize)
{
return SetWindowSize(SO_SNDBUF, nWindowSize);
};
/// Disable the Nagle algorithm (Set TCP_NODELAY to true)
/// @return false if failed to set socket option otherwise return true;
bool DisableNagleAlgoritm();
/// Enable the Nagle algorithm (Set TCP_NODELAY to false)
/// @return false if failed to set socket option otherwise return true;
bool EnableNagleAlgoritm();
/// Disable the Nagle algorithm (Set TCP_NODELAY to true)
/// @return false if failed to set socket option otherwise return true;
bool DisableNagleAlgoritm();
/// Enable the Nagle algorithm (Set TCP_NODELAY to false)
/// @return false if failed to set socket option otherwise return true;
bool EnableNagleAlgoritm();
protected:
/// Set internal socket error to that specified error
/// @param error type of error
void SetSocketError(CSimpleSocket::CSocketError error) {
m_socketErrno = error;
};
/// Set internal socket error to that specified error
/// @param error type of error
void SetSocketError(CSimpleSocket::CSocketError error)
{
m_socketErrno = error;
};
/// Set object socket handle to that specified as parameter
/// @param socket value of socket descriptor
void SetSocketHandle(SOCKET socket) {
m_socket = socket;
};
/// Set object socket handle to that specified as parameter
/// @param socket value of socket descriptor
void SetSocketHandle(SOCKET socket)
{
m_socket = socket;
};
private:
/// Generic function used to get the send/receive window size
/// @return zero on failure else the number of bytes of the TCP window size if successful.
uint32 GetWindowSize(uint32 nOptionName);
/// Generic function used to get the send/receive window size
/// @return zero on failure else the number of bytes of the TCP window size if successful.
uint32 GetWindowSize(uint32 nOptionName);
/// Generic function used to set the send/receive window size
/// @return zero on failure else the number of bytes of the TCP window size if successful.
uint32 SetWindowSize(uint32 nOptionName, uint32 nWindowSize);
/// Generic function used to set the send/receive window size
/// @return zero on failure else the number of bytes of the TCP window size if successful.
uint32 SetWindowSize(uint32 nOptionName, uint32 nWindowSize);
/// Attempts to send at most nNumItem blocks described by sendVector
/// to the socket descriptor associated with the socket object.
/// @param sendVector pointer to an array of iovec structures
/// @param nNumItems number of items in the vector to process
/// <br>\b Note: This implementation is for systems that don't natively
/// support this functionality.
/// @return number of bytes actually sent, return of zero means the
/// connection has been shutdown on the other side, and a return of -1
/// means that an error has occurred.
int32 Writev(const struct iovec *pVector, size_t nCount);
/// Attempts to send at most nNumItem blocks described by sendVector
/// to the socket descriptor associated with the socket object.
/// @param sendVector pointer to an array of iovec structures
/// @param nNumItems number of items in the vector to process
/// <br>\b Note: This implementation is for systems that don't natively
/// support this functionality.
/// @return number of bytes actually sent, return of zero means the
/// connection has been shutdown on the other side, and a return of -1
/// means that an error has occurred.
int32 Writev(const struct iovec *pVector, size_t nCount);
/// Flush the socket descriptor owned by the object.
/// @return true data was successfully sent, else return false;
bool Flush();
/// Flush the socket descriptor owned by the object.
/// @return true data was successfully sent, else return false;
bool Flush();
CSimpleSocket *operator=(CSimpleSocket &socket);
CSimpleSocket *operator=(CSimpleSocket &socket);
protected:
SOCKET m_socket; /// socket handle
CSocketError m_socketErrno; /// number of last error
uint8 *m_pBuffer; /// internal send/receive buffer
int32 m_nBufferSize; /// size of internal send/receive buffer
int32 m_nSocketDomain; /// socket type PF_INET, PF_INET6
CSocketType m_nSocketType; /// socket type - UDP, TCP or RAW
int32 m_nBytesReceived; /// number of bytes received
int32 m_nBytesSent; /// number of bytes sent
uint32 m_nFlags; /// socket flags
bool m_bIsBlocking; /// is socket blocking
bool m_bIsMulticast; /// is the UDP socket multicast;
struct timeval m_stConnectTimeout; /// connection timeout
struct timeval m_stRecvTimeout; /// receive timeout
struct timeval m_stSendTimeout; /// send timeout
struct sockaddr_in m_stServerSockaddr; /// server address
struct sockaddr_in m_stClientSockaddr; /// client address
struct sockaddr_in m_stMulticastGroup; /// multicast group to bind to
struct linger m_stLinger; /// linger flag
CStatTimer m_timer; /// internal statistics.
SOCKET m_socket; /// socket handle
CSocketError m_socketErrno; /// number of last error
uint8 *m_pBuffer; /// internal send/receive buffer
int32 m_nBufferSize; /// size of internal send/receive buffer
int32 m_nSocketDomain; /// socket type PF_INET, PF_INET6
CSocketType m_nSocketType; /// socket type - UDP, TCP or RAW
int32 m_nBytesReceived; /// number of bytes received
int32 m_nBytesSent; /// number of bytes sent
uint32 m_nFlags; /// socket flags
bool m_bIsBlocking; /// is socket blocking
bool m_bIsMulticast; /// is the UDP socket multicast;
struct timeval m_stConnectTimeout; /// connection timeout
struct timeval m_stRecvTimeout; /// receive timeout
struct timeval m_stSendTimeout; /// send timeout
struct sockaddr_in m_stServerSockaddr; /// server address
struct sockaddr_in m_stClientSockaddr; /// client address
struct sockaddr_in m_stMulticastGroup; /// multicast group to bind to
struct linger m_stLinger; /// linger flag
CStatTimer m_timer; /// internal statistics.
#ifdef WIN32
WSADATA m_hWSAData; /// Windows
WSADATA m_hWSAData; /// Windows
#endif
fd_set m_writeFds; /// write file descriptor set
fd_set m_readFds; /// read file descriptor set
fd_set m_errorFds; /// error file descriptor set
fd_set m_writeFds; /// write file descriptor set
fd_set m_readFds; /// read file descriptor set
fd_set m_errorFds; /// error file descriptor set
};
#endif /* __SOCKET_H__ */

View File

@@ -46,21 +46,21 @@
#include <string.h>
#if WIN32
#include <winsock2.h>
#include <time.h>
#include <winsock2.h>
#include <time.h>
#endif
#ifdef _LINUX
#include <stdio.h>
#include <sys/time.h>
#include <stdio.h>
#include <sys/time.h>
#endif
#include "Host.h"
#if defined(WIN32)
#define GET_CLOCK_COUNT(x) QueryPerformanceCounter((LARGE_INTEGER *)x)
#define GET_CLOCK_COUNT(x) QueryPerformanceCounter((LARGE_INTEGER *)x)
#else
#define GET_CLOCK_COUNT(x) gettimeofday(x, NULL)
#define GET_CLOCK_COUNT(x) gettimeofday(x, NULL)
#endif
#define MILLISECONDS_CONVERSION 1000
@@ -68,47 +68,43 @@
/// Class to abstract socket communications in a cross platform manner.
/// This class is designed
class CStatTimer {
class CStatTimer
{
public:
CStatTimer()
{
};
CStatTimer(){};
~CStatTimer()
{
};
~CStatTimer(){};
void Initialize()
{
memset(&m_startTime, 0, sizeof(struct timeval));
memset(&m_endTime, 0, sizeof(struct timeval));
};
void Initialize()
{
memset(&m_startTime, 0, sizeof(struct timeval));
memset(&m_endTime, 0, sizeof(struct timeval));
};
struct timeval GetStartTime() { return m_startTime; };
void SetStartTime() { GET_CLOCK_COUNT(&m_startTime); };
struct timeval GetStartTime() { return m_startTime; };
void SetStartTime() { GET_CLOCK_COUNT(&m_startTime); };
struct timeval GetEndTime() { return m_endTime; };
void SetEndTime() { GET_CLOCK_COUNT(&m_endTime); };
struct timeval GetEndTime() { return m_endTime; };
void SetEndTime() { GET_CLOCK_COUNT(&m_endTime); };
uint32 GetMilliSeconds() { return (CalcTotalUSec() / MILLISECONDS_CONVERSION); };
uint32 GetMicroSeconds() { return (CalcTotalUSec()); };
uint32 GetSeconds() { return (CalcTotalUSec() / MICROSECONDS_CONVERSION); };
uint32 GetMilliSeconds() { return (CalcTotalUSec() / MILLISECONDS_CONVERSION); };
uint32 GetMicroSeconds() { return (CalcTotalUSec()); };
uint32 GetSeconds() { return (CalcTotalUSec() / MICROSECONDS_CONVERSION); };
uint32 GetCurrentTime()
{
struct timeval tmpTime;
GET_CLOCK_COUNT(&tmpTime);
return ((tmpTime.tv_sec * MICROSECONDS_CONVERSION) + tmpTime.tv_usec);
};
uint32 GetCurrentTime()
{
struct timeval tmpTime;
GET_CLOCK_COUNT(&tmpTime);
return ((tmpTime.tv_sec * MICROSECONDS_CONVERSION) + tmpTime.tv_usec);
};
private:
uint32 CalcTotalUSec() { return (((m_endTime.tv_sec - m_startTime.tv_sec) * MICROSECONDS_CONVERSION) +
(m_endTime.tv_usec - m_startTime.tv_usec)); };
uint32 CalcTotalUSec() { return (((m_endTime.tv_sec - m_startTime.tv_sec) * MICROSECONDS_CONVERSION) +
(m_endTime.tv_usec - m_startTime.tv_usec)); };
private:
struct timeval m_startTime;
struct timeval m_endTime;
struct timeval m_startTime;
struct timeval m_endTime;
};
#endif // __CSTATTIMER_H__
#endif // __CSTATTIMER_H__