10 #include <apps/tcpip/socket.h>
11 #include <sys/simulation/simulation_controller.h>
20 #include <sys/types.h>
21 #include <sys/socket.h>
22 #include <netinet/in.h>
23 #include <netinet/tcp.h>
24 #include <arpa/inet.h>
38 #define vsnprintf _vsnprintf
55 extern "C" void init_tcpip( shawn::SimulationController& sc )
66 bool Socket::init_windows_sockets_ =
true;
67 bool Socket::windows_sockets_initialized_ =
false;
68 int Socket::instance_count_ = 0;
73 Socket(std::string host,
int port)
105 if( init_windows_sockets_ && !windows_sockets_initialized_ )
108 if( WSAStartup(MAKEWORD(1, 1), &wsaData) != 0 )
110 windows_sockets_initialized_ =
true;
122 int sock =
static_cast<int>(socket( AF_INET, SOCK_STREAM, 0 ));
123 struct sockaddr_in self;
124 memset(&self, 0,
sizeof(self));
125 self.sin_family = AF_INET;
126 self.sin_port = htons(0);
127 self.sin_addr.s_addr = htonl(INADDR_ANY);
129 socklen_t address_len =
sizeof(self);
131 if ( bind(sock, (
struct sockaddr*) &self, address_len) < 0)
134 if ( getsockname(sock, (
struct sockaddr*) &self, &address_len) < 0)
135 BailOnSocketError(
"tcpip::Socket::getFreeSocketPort() Unable to get socket name");
136 const int port = ntohs(self.sin_port);
138 ::closesocket( sock );
169 && init_windows_sockets_ && instance_count_ == 0 )
171 windows_sockets_initialized_ =
false;
181 int e = WSAGetLastError();
182 std::string msg = GetWinsockErrorString( e );
184 std::string msg = strerror( errno );
202#pragma warning(disable: 4548)
211 FD_SET( (
unsigned int)sock, &fds );
217 int r = select( sock+1, &fds,
nullptr,
nullptr, &tv);
222 if( FD_ISSET( sock, &fds ) )
239 struct sockaddr_in client_addr;
241 int addrlen =
sizeof(client_addr);
243 socklen_t addrlen =
sizeof(client_addr);
248 struct sockaddr_in self;
251 server_socket_ =
static_cast<int>(socket( AF_INET, SOCK_STREAM, 0 ));
263 setsockopt(
server_socket_, SOL_SOCKET, SO_REUSEADDR, &reuseaddr,
sizeof(reuseaddr));
268 memset(&self, 0,
sizeof(self));
269 self.sin_family = AF_INET;
270 self.sin_port = htons((
unsigned short)
port_);
271 self.sin_addr.s_addr = htonl(INADDR_ANY);
274 if ( bind(
server_socket_, (
struct sockaddr*)&self,
sizeof(self)) != 0 )
291 setsockopt(
socket_, IPPROTO_TCP, TCP_NODELAY, (
const char*)&x,
sizeof(x));
313 if (ioctlsocket(
server_socket_, FIONBIO, &NonBlock) == SOCKET_ERROR)
314 BailOnSocketError(
"tcpip::Socket::set_blocking() Unable to initialize non blocking I/O");
334 struct addrinfo* servinfo;
335 struct addrinfo hints;
336 memset(&hints, 0,
sizeof hints);
337 hints.ai_family = AF_UNSPEC;
338 hints.ai_socktype = SOCK_STREAM;
339 hints.ai_flags = AI_PASSIVE;
341 if (getaddrinfo(
host_.c_str(), std::to_string(
port_).c_str(), &hints, &servinfo) != 0) {
345 for (
struct addrinfo* p = servinfo; p !=
nullptr; p = p->ai_next) {
346 socket_ = (int)socket(p->ai_family, p->ai_socktype, p->ai_protocol);
350 setsockopt(
socket_, IPPROTO_TCP, TCP_NODELAY, (
const char*)&x,
sizeof(x));
356 freeaddrinfo(servinfo);
383 send(
const std::vector<unsigned char> &buffer)
390 size_t numbytes = buffer.size();
391 unsigned char const *bufPtr = &buffer[0];
392 while( numbytes > 0 )
395 int bytesSent =
::send(
socket_, (
const char*)bufPtr,
static_cast<int>(numbytes), 0 );
402 numbytes -= bytesSent;
415 int length =
static_cast<int>(b.
size());
422 std::vector<unsigned char> msg;
423 msg.insert(msg.end(), length_storage.
begin(), length_storage.
end());
424 msg.insert(msg.end(), b.
begin(), b.
end());
432 recvAndCheck(
unsigned char *
const buffer, std::size_t len)
436 const int bytesReceived = recv(
socket_, (
char*)buffer,
static_cast<int>(len), 0 );
438 const int bytesReceived =
static_cast<int>(recv(
socket_, buffer, len, 0 ));
440 if( bytesReceived == 0 )
441 throw SocketException(
"tcpip::Socket::recvAndCheck @ recv: peer shutdown" );
442 if( bytesReceived < 0 )
445 return static_cast<size_t>(bytesReceived);
458 len -= bytesReceived;
459 buffer += bytesReceived;
472 std::cerr << label <<
" " << buffer.size() <<
" bytes via tcpip::Socket: [";
474 const std::vector<unsigned char>::const_iterator end = buffer.end();
475 for (std::vector<unsigned char>::const_iterator it = buffer.begin(); end != it; ++it)
476 std::cerr <<
" " <<
static_cast<int>(*it) <<
" ";
477 std::cerr <<
"]" << std::endl;
483 std::vector<unsigned char>
487 std::vector<unsigned char> buffer;
495 buffer.resize(bufSize);
496 const size_t bytesReceived =
recvAndCheck(&buffer[0], bufSize);
498 buffer.resize(bytesReceived);
515 std::vector<unsigned char> buffer(
lengthLen);
520 const int totalLen = length_storage.
readInt();
524 buffer.resize(totalLen);
561 GetWinsockErrorString(
int err)
566 case 0:
return "No error";
567 case WSAEINTR:
return "Interrupted system call";
568 case WSAEBADF:
return "Bad file number";
569 case WSAEACCES:
return "Permission denied";
570 case WSAEFAULT:
return "Bad address";
571 case WSAEINVAL:
return "Invalid argument";
572 case WSAEMFILE:
return "Too many open sockets";
573 case WSAEWOULDBLOCK:
return "Operation would block";
574 case WSAEINPROGRESS:
return "Operation now in progress";
575 case WSAEALREADY:
return "Operation already in progress";
576 case WSAENOTSOCK:
return "Socket operation on non-socket";
577 case WSAEDESTADDRREQ:
return "Destination address required";
578 case WSAEMSGSIZE:
return "Message too long";
579 case WSAEPROTOTYPE:
return "Protocol wrong type for socket";
580 case WSAENOPROTOOPT:
return "Bad protocol option";
581 case WSAEPROTONOSUPPORT:
return "Protocol not supported";
582 case WSAESOCKTNOSUPPORT:
return "Socket type not supported";
583 case WSAEOPNOTSUPP:
return "Operation not supported on socket";
584 case WSAEPFNOSUPPORT:
return "Protocol family not supported";
585 case WSAEAFNOSUPPORT:
return "Address family not supported";
586 case WSAEADDRINUSE:
return "Address already in use";
587 case WSAEADDRNOTAVAIL:
return "Can't assign requested address";
588 case WSAENETDOWN:
return "Network is down";
589 case WSAENETUNREACH:
return "Network is unreachable";
590 case WSAENETRESET:
return "Net Socket reset";
591 case WSAECONNABORTED:
return "Software caused tcpip::Socket abort";
592 case WSAECONNRESET:
return "Socket reset by peer";
593 case WSAENOBUFS:
return "No buffer space available";
594 case WSAEISCONN:
return "Socket is already connected";
595 case WSAENOTCONN:
return "Socket is not connected";
596 case WSAESHUTDOWN:
return "Can't send after socket shutdown";
597 case WSAETOOMANYREFS:
return "Too many references, can't splice";
598 case WSAETIMEDOUT:
return "Socket timed out";
599 case WSAECONNREFUSED:
return "Socket refused";
600 case WSAELOOP:
return "Too many levels of symbolic links";
601 case WSAENAMETOOLONG:
return "File name too long";
602 case WSAEHOSTDOWN:
return "Host is down";
603 case WSAEHOSTUNREACH:
return "No route to host";
604 case WSAENOTEMPTY:
return "Directory not empty";
605 case WSAEPROCLIM:
return "Too many processes";
606 case WSAEUSERS:
return "Too many users";
607 case WSAEDQUOT:
return "Disc quota exceeded";
608 case WSAESTALE:
return "Stale NFS file handle";
609 case WSAEREMOTE:
return "Too many levels of remote in path";
610 case WSASYSNOTREADY:
return "Network system is unavailable";
611 case WSAVERNOTSUPPORTED:
return "Winsock version out of range";
612 case WSANOTINITIALISED:
return "WSAStartup not yet called";
613 case WSAEDISCON:
return "Graceful shutdown in progress";
614 case WSAHOST_NOT_FOUND:
return "Host not found";
615 case WSANO_DATA:
return "No host data of that type was found";
void printBufferOnVerbose(const std::vector< unsigned char > buffer, const std::string &label) const
Print label and buffer to stderr if Socket::verbose_ is set.
bool receiveExact(Storage &)
Receive a complete TraCI message from Socket::socket_.
std::vector< unsigned char > receive(int bufSize=2048)
Receive up to bufSize available bytes from Socket::socket_.
bool datawaiting(int sock) const
size_t recvAndCheck(unsigned char *const buffer, std::size_t len) const
Receive up to len available bytes from Socket::socket_.
static void BailOnSocketError(std::string context)
static int getFreeSocketPort()
Returns an free port on the system.
void sendExact(const Storage &)
bool has_client_connection() const
void connect()
Connects to host_:port_.
static const int lengthLen
Length of the message length part of a TraCI message.
Socket * accept(const bool create=false)
Wait for a incoming connection to port_.
void receiveComplete(unsigned char *const buffer, std::size_t len) const
Receive len bytes from Socket::socket_.
void send(const std::vector< unsigned char > &buffer)
Socket(std::string host, int port)
Constructor that prepare to connect to host:port.
virtual void writePacket(unsigned char *packet, int length)
StorageType::const_iterator begin() const
virtual void writeInt(int)
StorageType::const_iterator end() const
StorageType::size_type size() const