46#include <sys/socket.h>
48#include <netinet/in.h>
52#pragma GCC diagnostic ignored "-Wconversion"
61class SocketImpl:
public util::NonCopyable
64 typedef Socket::TPort TPort;
67 socket_(invalidSocket)
77 catch (
const std::exception& error)
79 std::cerr <<
"[LASS RUN MSG] WARNING: closeSocket() failed: " << error.what();
83 void bind(
const std::string& address, TPort portNumber)
90 addr.sin_addr.s_addr = htonl(INADDR_ANY);
94 ::hostent* other = gethostbyname(address.c_str());
97 LASS_THROW_EX(SocketError,
"could not bind " << address <<
":" << portNumber <<
" : failed to lookup hostname.");
99 addr.sin_addr = *(in_addr*) other->h_addr;
101 addr.sin_family = AF_INET;
102 addr.sin_port = htons(portNumber);
104 if (::bind(socket_,
reinterpret_cast<sockaddr*
>(&addr),
sizeof(addr)) != 0)
107 LASS_THROW_EX(SocketError,
"Failed to bind socket to port " << portNumber
112 std::string address()
const
142 LASS_ASSERT(socket_ != invalidSocket);
143 if (::listen(socket_, SOMAXCONN) != 0)
150 void accept(SocketImpl* connection)
const
152 LASS_ASSERT(socket_ != invalidSocket);
153 int socket = ::accept(socket_, 0, 0);
154 if (socket == invalidSocket)
159 LASS_ASSERT(connection);
160 connection->socket_ = socket;
163 void connect(
const std::string& ipAddress,
unsigned short portNumber)
167 ::hostent* other = gethostbyname(ipAddress.c_str());
170 LASS_THROW_EX(SocketError,
"could not connect " << ipAddress <<
":" << portNumber <<
" : failed to lookup hostname.");
174 dest.sin_addr = *(in_addr*) other->h_addr;
175 dest.sin_family = PF_INET;
176 dest.sin_port = htons(portNumber);
177 const int ret = ::connect(socket_,
reinterpret_cast<sockaddr*
>(&dest),
sizeof(dest));
181 LASS_THROW_EX(SocketError,
"Could not connect " << ipAddress <<
":" << portNumber
186 int send(
const void* begin,
int length)
const
188 LASS_ASSERT(socket_ != invalidSocket);
189 const int ret = ::send(socket_,
static_cast<const char*
>(begin), length, 0);
195 LASS_ASSERT(ret >= 0);
199 int receive(
void* begin,
int length)
const
201 const int ret = ::recv(socket_,
static_cast<char*
>(begin), length, 0);
207 LASS_ASSERT(ret >= 0);
211 int sizeSendBuffer()
const
218 if (socket_ != invalidSocket)
222 socket_ = socket(AF_INET, SOCK_STREAM, 0);
223 if (socket_ == invalidSocket)
232 if (socket_ == invalidSocket)
236 const int ret = close(socket_);
242 socket_ = invalidSocket;
247 enum { invalidSocket = -1 };
const std::string lass_strerror(int errnum)
returns message associated to an CLIB error code
int lass_errno()
returns CLIB errno
streams, binary streams, vrmlstreams, ...
Library for Assembled Shared Sources.