2 simgear::Socket, adapted from PLIB Socket by James Turner
3 Copyright (C) 2010 James Turner
5 PLIB - A Suite of Portable Game Libraries
6 Copyright (C) 1998,2002 Steve Baker
8 This library is free software; you can redistribute it and/or
9 modify it under the terms of the GNU Library General Public
10 License as published by the Free Software Foundation; either
11 version 2 of the License, or (at your option) any later version.
13 This library is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Library General Public License for more details.
18 You should have received a copy of the GNU Library General Public
19 License along with this library; if not, write to the Free Software
20 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 # include <simgear_config.h>
27 #include <simgear/compiler.h>
28 #include "raw_socket.hxx"
30 #if defined(_WIN32) && !defined(__CYGWIN__)
31 # define WINSOCK // use winsock convetions, otherwise standard POSIX
38 #include <cstdio> // for snprintf
42 # include <winsock2.h>
43 # include <ws2tcpip.h>
46 # include <sys/types.h>
47 # include <sys/socket.h>
48 # include <netinet/in.h>
49 # include <arpa/inet.h>
50 # include <sys/time.h>
56 #if defined(_MSC_VER) && !defined(socklen_t)
60 #include <simgear/debug/logstream.hxx>
61 #include <simgear/structure/exception.hxx>
66 IPAddress::IPAddress ( const char* host, int port )
71 IPAddress::IPAddress( const IPAddress& other ) :
75 addr = (struct sockaddr_in*) malloc(sizeof(struct sockaddr_in));
76 memcpy(addr, other.addr, sizeof(struct sockaddr_in));
80 const IPAddress& IPAddress::operator=(const IPAddress& other)
88 addr = (struct sockaddr_in*) malloc(sizeof(struct sockaddr_in));
89 memcpy(addr, other.addr, sizeof(struct sockaddr_in));
95 void IPAddress::set ( const char* host, int port )
97 addr = (struct sockaddr_in*) malloc(sizeof(struct sockaddr_in));
98 memset(addr, 0, sizeof(struct sockaddr_in));
100 addr->sin_family = AF_INET ;
101 addr->sin_port = htons (port);
103 /* Convert a string specifying a host name or one of a few symbolic
104 ** names to a numeric IP address. This usually calls getaddrinfo()
105 ** to do the work; the names "" and "<broadcast>" are special.
108 if (!host || host[0] == '\0') {
109 addr->sin_addr.s_addr = INADDR_ANY;
113 if (strcmp(host, "<broadcast>") == 0) {
114 addr->sin_addr.s_addr = INADDR_BROADCAST;
118 struct addrinfo hints;
119 memset(&hints, 0, sizeof(struct addrinfo));
120 hints.ai_family = AF_INET;
122 struct addrinfo* result0 = NULL;
123 int err = getaddrinfo(host, NULL, &hints, &result0);
125 SG_LOG(SG_IO, SG_WARN, "getaddrinfo failed for '" << host << "' : " << gai_strerror(err));
127 struct addrinfo* result;
128 for (result = result0; result != NULL; result = result->ai_next) {
129 if (result->ai_family != AF_INET) { // only accept IP4 for the moment
133 if (result->ai_addrlen != getAddrLen()) {
134 SG_LOG(SG_IO, SG_ALERT, "mismatch in socket address sizes: got " <<
135 result->ai_addrlen << ", expected " << getAddrLen());
139 memcpy(addr, result->ai_addr, result->ai_addrlen);
141 } // of getaddrinfo results iteration
142 } // of getaddrinfo succeeded
144 freeaddrinfo(result0);
145 addr->sin_port = htons (port); // fix up port after getaddrinfo
148 IPAddress::~IPAddress()
155 /* Create a string object representing an IP address.
156 This is always a string of the form 'dd.dd.dd.dd' (with variable
159 const char* IPAddress::getHost () const
161 static char buf [32];
162 long x = ntohl(addr->sin_addr.s_addr);
163 sprintf(buf, "%d.%d.%d.%d",
164 (int) (x>>24) & 0xff, (int) (x>>16) & 0xff,
165 (int) (x>> 8) & 0xff, (int) (x>> 0) & 0xff );
169 unsigned int IPAddress::getIP () const
171 return addr->sin_addr.s_addr;
174 unsigned int IPAddress::getPort() const
176 return ntohs(addr->sin_port);
179 unsigned int IPAddress::getFamily () const
181 return addr->sin_family;
184 const char* IPAddress::getLocalHost ()
186 //gethostbyname(gethostname())
189 memset(buf, 0, sizeof(buf));
190 gethostname(buf, sizeof(buf)-1);
191 const hostent *hp = gethostbyname(buf);
193 if (hp && *hp->h_addr_list)
195 in_addr addr = *((in_addr*)*hp->h_addr_list);
196 const char* host = inet_ntoa(addr);
206 bool IPAddress::getBroadcast () const
208 return (addr->sin_addr.s_addr == INADDR_BROADCAST);
211 unsigned int IPAddress::getAddrLen() const
213 return sizeof(struct sockaddr_in);
216 struct sockaddr* IPAddress::getAddr() const
218 return (struct sockaddr*) addr;
233 void Socket::setHandle (int _handle)
240 bool Socket::open ( bool stream )
243 handle = ::socket ( AF_INET, (stream? SOCK_STREAM: SOCK_DGRAM), 0 ) ;
245 // Jan 26, 2010: Patch to avoid the problem of the socket resource not
246 // yet being available if the program is restarted quickly after being
249 // Reference: http://www.unixguide.net/network/socketfaq/4.5.shtml
251 // Also required for joining multicast domains
254 #if defined(_WIN32) || defined(__CYGWIN__)
255 setsockopt( handle, SOL_SOCKET, SO_REUSEADDR, (char *)&opt_boolean,
256 sizeof(opt_boolean) );
258 setsockopt( handle, SOL_SOCKET, SO_REUSEADDR, &opt_boolean,
259 sizeof(opt_boolean) );
263 return (handle != -1);
267 void Socket::setBlocking ( bool blocking )
269 assert ( handle != -1 ) ;
272 u_long nblocking = blocking? 0: 1;
273 ::ioctlsocket(handle, FIONBIO, &nblocking);
276 int delay_flag = ::fcntl (handle, F_GETFL, 0);
279 delay_flag &= (~O_NDELAY);
281 delay_flag |= O_NDELAY;
283 ::fcntl (handle, F_SETFL, delay_flag);
288 void Socket::setBroadcast ( bool broadcast )
290 assert ( handle != -1 ) ;
294 #if defined(_WIN32) || defined(__CYGWIN__)
295 result = ::setsockopt( handle, SOL_SOCKET, SO_BROADCAST, (char*)&one, sizeof(one) );
297 result = ::setsockopt( handle, SOL_SOCKET, SO_BROADCAST, &one, sizeof(one) );
300 result = ::setsockopt( handle, SOL_SOCKET, SO_BROADCAST, NULL, 0 );
304 throw sg_exception("Socket::setBroadcast failed");
309 int Socket::bind ( const char* host, int port )
312 assert ( handle != -1 ) ;
313 IPAddress addr ( host, port ) ;
315 #if !defined(WINSOCK)
316 if( (result = ::bind(handle, addr.getAddr(), addr.getAddrLen() ) ) < 0 ) {
317 SG_LOG(SG_IO, SG_ALERT, "bind(" << addr.getHost() << ":" << addr.getPort() << ") failed. Errno " << errno << " (" << strerror(errno) << ")");
322 // 224.0.0.0 - 239.255.255.255 are multicast
323 // Usage of 239.x.x.x is recommended for local scope
324 // Reference: http://tools.ietf.org/html/rfc5771
325 if( ntohl(addr.getIP()) >= 0xe0000000 && ntohl(addr.getIP()) <= 0xefffffff ) {
328 struct sockaddr_in a;
329 a.sin_addr.S_un.S_addr = INADDR_ANY;
330 a.sin_family = AF_INET;
331 a.sin_port = htons(port);
333 if( (result = ::bind(handle,(const sockaddr*)&a,sizeof(a))) < 0 ) {
334 SG_LOG(SG_IO, SG_ALERT, "bind(any:" << port << ") failed. Errno " << errno << " (" << strerror(errno) << ")");
340 mreq.imr_multiaddr.s_addr = addr.getIP();
341 mreq.imr_interface.s_addr = htonl(INADDR_ANY);
342 if( (result=::setsockopt(getHandle(), IPPROTO_IP, IP_ADD_MEMBERSHIP, (const char *)&mreq, sizeof(mreq))) != 0 ) {
343 SG_LOG(SG_IO, SG_ALERT, "setsockopt(IP_ADD_MEMBERSHIP) failed. Errno " << errno << " (" << strerror(errno) << ")");
348 else if( (result = ::bind(handle,addr.getAddr(), addr.getAddrLen())) < 0 ) {
349 SG_LOG(SG_IO, SG_ALERT, "bind(" << host << ":" << port << ") failed. Errno " << errno << " (" << strerror(errno) << ")");
358 int Socket::listen ( int backlog )
360 assert ( handle != -1 ) ;
361 return ::listen(handle,backlog);
365 int Socket::accept ( IPAddress* addr )
367 assert ( handle != -1 ) ;
371 return ::accept(handle,NULL,NULL);
375 socklen_t addr_len = addr->getAddrLen(); ;
376 return ::accept(handle, addr->getAddr(), &addr_len);
381 int Socket::connect ( const char* host, int port )
383 IPAddress addr ( host, port ) ;
384 return connect ( &addr );
388 int Socket::connect ( IPAddress* addr )
390 assert ( handle != -1 ) ;
391 if ( addr->getBroadcast() ) {
392 setBroadcast( true );
394 return ::connect(handle, addr->getAddr(), addr->getAddrLen() );
398 int Socket::send (const void * buffer, int size, int flags)
400 assert ( handle != -1 ) ;
401 return ::send (handle, (const char*)buffer, size, flags);
405 int Socket::sendto ( const void * buffer, int size,
406 int flags, const IPAddress* to )
408 assert ( handle != -1 ) ;
409 return ::sendto(handle,(const char*)buffer,size,flags,
410 (const sockaddr*) to->getAddr(), to->getAddrLen());
414 int Socket::recv (void * buffer, int size, int flags)
416 assert ( handle != -1 ) ;
417 return ::recv (handle, (char*)buffer, size, flags);
421 int Socket::recvfrom ( void * buffer, int size,
422 int flags, IPAddress* from )
424 assert ( handle != -1 ) ;
425 socklen_t fromlen = (socklen_t) from->getAddrLen() ;
426 return ::recvfrom(handle,(char*)buffer,size,flags, from->getAddr(),&fromlen);
430 void Socket::close (void)
435 ::closesocket( handle );
444 bool Socket::isNonBlockingError ()
447 int wsa_errno = WSAGetLastError();
448 if ( wsa_errno != 0 )
451 SG_LOG(SG_IO, SG_WARN, "isNonBlockingError: WSAGetLastError():" << wsa_errno);
453 case WSAEWOULDBLOCK: // always == NET_EAGAIN?
462 case EWOULDBLOCK: // always == NET_EAGAIN?
473 //////////////////////////////////////////////////////////////////////
475 // modified version by os
477 //////////////////////////////////////////////////////////////////////
478 int Socket::select ( Socket** reads, Socket** writes, int timeout )
491 for ( i=0; reads[i]; i++ )
493 int fd = reads[i]->getHandle();
501 for ( i=0; writes[i]; i++ )
503 int fd = writes[i]->getHandle();
512 /* Set up the timeout */
514 tv.tv_sec = timeout/1000;
515 tv.tv_usec = (timeout%1000)*1000;
517 // It bothers me that select()'s first argument does not appear to
518 // work as advertised... [it hangs like this if called with
519 // anything less than FD_SETSIZE, which seems wasteful?]
521 // Note: we ignore the 'exception' fd_set - I have never had a
522 // need to use it. The name is somewhat misleading - the only
523 // thing I have ever seen it used for is to detect urgent data -
524 // which is an unportable feature anyway.
526 retval = ::select (FD_SETSIZE, &r, &w, 0, &tv);
528 //remove sockets that had no activity
534 for ( k=i=0; reads[i]; i++ )
536 int fd = reads[i]->getHandle();
537 if ( FD_ISSET (fd, &r) )
539 reads[k++] = reads[i];
548 for ( k=i=0; writes[i]; i++ )
550 int fd = writes[i]->getHandle();
551 if ( FD_ISSET (fd, &w) )
553 writes[k++] = writes[i];
560 if (retval == 0) // timeout
562 if (retval == -1)// error
569 /* Init/Exit functions */
571 static void netExit ( void )
574 /* Clean up windows networking */
575 if ( WSACleanup() == SOCKET_ERROR ) {
576 if ( WSAGetLastError() == WSAEINPROGRESS ) {
577 WSACancelBlockingCall();
584 int Socket::initSockets()
587 /* Start up the windows networking */
588 WORD version_wanted = MAKEWORD(1,1);
591 if ( WSAStartup(version_wanted, &wsaData) != 0 ) {
592 throw sg_exception("WinSock initialization failed");
601 } // of namespace simgear