15 #ifndef INCG_IRIS_IUTEST_SOCKET_HPP_77654A63_0A08_43CA_950E_61232690163B_
16 #define INCG_IRIS_IUTEST_SOCKET_HPP_77654A63_0A08_43CA_950E_61232690163B_
23 #ifdef IUTEST_HAS_SOCKET
25 #ifdef IUTEST_OS_WINDOWS
26 # include <winsock2.h>
27 # include <ws2tcpip.h>
29 # include <arpa/inet.h>
34 # if defined(IUTEST_OS_WINDOWS_MOBILE)
35 # pragma comment(lib, "ws2.lib")
37 # pragma comment(lib, "ws2_32.lib")
53 #ifdef IUTEST_OS_WINDOWS
54 typedef SOCKET descriptor_t;
57 #if !defined(IUTEST_NO_INCLASS_MEMBER_INITIALIZATION)
58 static const descriptor_t INVALID_DESCRIPTOR = INVALID_SOCKET;
60 enum { INVALID_DESCRIPTOR = INVALID_SOCKET };
64 typedef int descriptor_t;
65 typedef size_t length_t;
67 #if !defined(IUTEST_NO_INCLASS_MEMBER_INITIALIZATION)
68 static const descriptor_t INVALID_DESCRIPTOR = -1;
70 enum { INVALID_DESCRIPTOR = -1 };
75 BasicSocket() : m_socket(INVALID_DESCRIPTOR)
77 #ifdef IUTEST_OS_WINDOWS
79 (void)WSAStartup(MAKEWORD(2, 2), &wsaData);
85 #ifdef IUTEST_OS_WINDOWS
90 bool Open(
const char* host,
const char* port)
92 if( m_socket != INVALID_DESCRIPTOR )
96 addrinfo* servinfo = NULL;
98 memset(&hints, 0,
sizeof(hints));
99 hints.ai_family = AF_UNSPEC;
100 hints.ai_socktype = SOCK_STREAM;
101 const int err_no = getaddrinfo(host, port, &hints, &servinfo);
107 for( addrinfo* curr=servinfo; curr != NULL; curr = curr->ai_next )
109 const descriptor_t fd = socket(curr->ai_family, curr->ai_socktype, curr->ai_protocol);
110 if( fd != INVALID_DESCRIPTOR )
112 if( connect(fd, curr->ai_addr,
static_cast<length_t
>(curr->ai_addrlen)) != -1 )
120 freeaddrinfo(servinfo);
121 return (m_socket != INVALID_DESCRIPTOR);
126 m_socket = INVALID_DESCRIPTOR;
128 void CheckLastError()
130 #ifdef IUTEST_OS_WINDOWS
131 const int le = WSAGetLastError();
136 static int Close(descriptor_t d)
138 #ifdef IUTEST_OS_WINDOWS
139 return closesocket(d);
148 return m_socket != INVALID_DESCRIPTOR;
151 descriptor_t m_socket;
159 class SocketWriter :
virtual public BasicSocket
165 bool Send(const ::std::string& message)
167 return Write(message.c_str(), message.length(), 1u);
169 bool SendLn(const ::std::string& message)
171 #ifdef IUTEST_OS_WINDOWS
172 return Send(message +
"\r\n");
174 return Send(message +
"\r\n");
185 const int size_ =
static_cast<int>(size);
186 for(
size_t i=0; i < cnt; ++i )
188 #ifdef IUTEST_OS_WINDOWS
189 if( send(m_socket,
static_cast<const char*
>(buf), size_, 0) == SOCKET_ERROR )
195 if( write(m_socket, buf, size_) == -1 )
210 class SocketReader :
virtual public BasicSocket
215 bool Read(
void* buf,
size_t size)
221 const int size_ =
static_cast<int>(size);
222 #ifdef IUTEST_OS_WINDOWS
223 if( recv(m_socket,
static_cast<char*
>(buf), size_, 0) == SOCKET_ERROR )
229 if( read(m_socket, buf, size_) == -1 )
243 class Socket :
public SocketWriter,
public SocketReader
254 #endif // INCG_IRIS_IUTEST_SOCKET_HPP_77654A63_0A08_43CA_950E_61232690163B_