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)
62 #include <simgear/debug/logstream.hxx>
63 #include <simgear/structure/exception.hxx>
64 #include <simgear/threads/SGThread.hxx>
68 class Resolver : public SGThread
71 static Resolver* instance()
73 if (!static_instance) {
74 static_instance = new Resolver;
75 atexit(&Resolver::cleanup);
76 static_instance->start();
79 return static_instance;
84 static_instance->shutdown();
85 static_instance->join();
101 simgear::IPAddress* lookup(const string& host)
103 simgear::IPAddress* result = NULL;
105 AddressCache::iterator it = _cache.find(host);
106 if (it == _cache.end()) {
107 _cache[host] = NULL; // mark as needing looked up
108 _wait.signal(); // if the thread was sleeping, poke it
116 simgear::IPAddress* lookupSync(const string& host)
118 simgear::IPAddress* result = NULL;
120 AddressCache::iterator it = _cache.find(host);
121 if (it == _cache.end()) {
123 result = new simgear::IPAddress;
124 bool ok = lookupHost(host.c_str(), *result);
127 _cache[host] = result; // mark as needing looked up
132 } else { // found in cache, easy
140 * run method waits on a condition (_wait), and when awoken,
141 * finds any unresolved entries in _cache, resolves them, and goes
148 AddressCache::iterator it;
150 for (it = _cache.begin(); it != _cache.end(); ++it) {
151 if (it->second == NULL) {
152 string h = it->first;
155 simgear::IPAddress* addr = new simgear::IPAddress;
156 // may take seconds or even minutes!
157 lookupHost(h.c_str(), *addr);
160 // cahce may have changed while we had the lock released -
161 // so iterators may be invalid: restart the traversal
164 } // of found un-resolved entry
165 } // of un-resolved address iteration
167 } // of thread run loop
171 static Resolver* static_instance;
174 * The actual synchronous, blocking host lookup function
175 * do *not* call this with any locks (mutexs) held, since depending
176 * on local system configuration / network availability, it
177 * may block for seconds or minutes.
179 bool lookupHost(const char* host, simgear::IPAddress& addr)
181 struct addrinfo hints;
182 memset(&hints, 0, sizeof(struct addrinfo));
183 hints.ai_family = AF_INET;
186 struct addrinfo* result0 = NULL;
187 int err = getaddrinfo(host, NULL, &hints, &result0);
189 SG_LOG(SG_IO, SG_WARN, "getaddrinfo failed for '" << host << "' : " << gai_strerror(err));
192 struct addrinfo* result;
193 for (result = result0; result != NULL; result = result->ai_next) {
194 if (result->ai_family != AF_INET) { // only accept IP4 for the moment
198 if (result->ai_addrlen != addr.getAddrLen()) {
199 SG_LOG(SG_IO, SG_ALERT, "mismatch in socket address sizes: got " <<
200 result->ai_addrlen << ", expected " << addr.getAddrLen());
204 memcpy(addr.getAddr(), result->ai_addr, result->ai_addrlen);
207 } // of getaddrinfo results iteration
208 } // of getaddrinfo succeeded
210 freeaddrinfo(result0);
215 SGWaitCondition _wait;
217 typedef std::map<string, simgear::IPAddress*> AddressCache;
222 Resolver* Resolver::static_instance = NULL;
224 } // of anonymous namespace
229 IPAddress::IPAddress ( const char* host, int port )
234 IPAddress::IPAddress( const IPAddress& other ) :
238 addr = (struct sockaddr_in*) malloc(sizeof(struct sockaddr_in));
239 memcpy(addr, other.addr, sizeof(struct sockaddr_in));
243 const IPAddress& IPAddress::operator=(const IPAddress& other)
251 addr = (struct sockaddr_in*) malloc(sizeof(struct sockaddr_in));
252 memcpy(addr, other.addr, sizeof(struct sockaddr_in));
258 void IPAddress::set ( const char* host, int port )
260 addr = (struct sockaddr_in*) malloc(sizeof(struct sockaddr_in));
261 memset(addr, 0, sizeof(struct sockaddr_in));
263 addr->sin_family = AF_INET ;
264 addr->sin_port = htons (port);
266 /* Convert a string specifying a host name or one of a few symbolic
267 ** names to a numeric IP address. This usually calls getaddrinfo()
268 ** to do the work; the names "" and "<broadcast>" are special.
271 if (!host || host[0] == '\0') {
272 addr->sin_addr.s_addr = INADDR_ANY;
276 if (strcmp(host, "<broadcast>") == 0) {
277 addr->sin_addr.s_addr = INADDR_BROADCAST;
282 IPAddress* cached = Resolver::instance()->lookupSync(host);
284 memcpy(addr, cached->getAddr(), cached->getAddrLen());
287 addr->sin_port = htons (port); // fix up port after getaddrinfo
290 IPAddress::~IPAddress()
297 bool IPAddress::lookupNonblocking(const char* host, IPAddress& addr)
299 IPAddress* cached = Resolver::instance()->lookup(host);
308 /* Create a string object representing an IP address.
309 This is always a string of the form 'dd.dd.dd.dd' (with variable
312 const char* IPAddress::getHost () const
314 static char buf [32];
315 long x = ntohl(addr->sin_addr.s_addr);
316 sprintf(buf, "%d.%d.%d.%d",
317 (int) (x>>24) & 0xff, (int) (x>>16) & 0xff,
318 (int) (x>> 8) & 0xff, (int) (x>> 0) & 0xff );
322 unsigned int IPAddress::getIP () const
324 return addr->sin_addr.s_addr;
327 unsigned int IPAddress::getPort() const
329 return ntohs(addr->sin_port);
332 void IPAddress::setPort(int port)
334 addr->sin_port = htons(port);
337 unsigned int IPAddress::getFamily () const
339 return addr->sin_family;
342 const char* IPAddress::getLocalHost ()
344 //gethostbyname(gethostname())
347 memset(buf, 0, sizeof(buf));
348 gethostname(buf, sizeof(buf)-1);
349 const hostent *hp = gethostbyname(buf);
351 if (hp && *hp->h_addr_list)
353 in_addr addr = *((in_addr*)*hp->h_addr_list);
354 const char* host = inet_ntoa(addr);
364 bool IPAddress::getBroadcast () const
366 return (addr->sin_addr.s_addr == INADDR_BROADCAST);
369 unsigned int IPAddress::getAddrLen() const
371 return sizeof(struct sockaddr_in);
374 struct sockaddr* IPAddress::getAddr() const
377 addr = (struct sockaddr_in*) malloc(sizeof(struct sockaddr_in));
378 memset(addr, 0, sizeof(struct sockaddr_in));
381 return (struct sockaddr*) addr;
396 void Socket::setHandle (int _handle)
403 bool Socket::open ( bool stream )
406 handle = ::socket ( AF_INET, (stream? SOCK_STREAM: SOCK_DGRAM), 0 ) ;
408 // Jan 26, 2010: Patch to avoid the problem of the socket resource not
409 // yet being available if the program is restarted quickly after being
412 // Reference: http://www.unixguide.net/network/socketfaq/4.5.shtml
414 // Also required for joining multicast domains
417 #if defined(_WIN32) || defined(__CYGWIN__)
418 setsockopt( handle, SOL_SOCKET, SO_REUSEADDR, (char *)&opt_boolean,
419 sizeof(opt_boolean) );
421 setsockopt( handle, SOL_SOCKET, SO_REUSEADDR, &opt_boolean,
422 sizeof(opt_boolean) );
426 return (handle != -1);
430 void Socket::setBlocking ( bool blocking )
432 assert ( handle != -1 ) ;
435 u_long nblocking = blocking? 0: 1;
436 ::ioctlsocket(handle, FIONBIO, &nblocking);
439 int delay_flag = ::fcntl (handle, F_GETFL, 0);
442 delay_flag &= (~O_NDELAY);
444 delay_flag |= O_NDELAY;
446 ::fcntl (handle, F_SETFL, delay_flag);
451 void Socket::setBroadcast ( bool broadcast )
453 assert ( handle != -1 ) ;
457 #if defined(_WIN32) || defined(__CYGWIN__)
458 result = ::setsockopt( handle, SOL_SOCKET, SO_BROADCAST, (char*)&one, sizeof(one) );
460 result = ::setsockopt( handle, SOL_SOCKET, SO_BROADCAST, &one, sizeof(one) );
463 result = ::setsockopt( handle, SOL_SOCKET, SO_BROADCAST, NULL, 0 );
467 throw sg_exception("Socket::setBroadcast failed");
472 int Socket::bind ( const char* host, int port )
475 assert ( handle != -1 ) ;
476 IPAddress addr ( host, port ) ;
478 #if !defined(WINSOCK)
479 if( (result = ::bind(handle, addr.getAddr(), addr.getAddrLen() ) ) < 0 ) {
480 SG_LOG(SG_IO, SG_ALERT, "bind(" << addr.getHost() << ":" << addr.getPort() << ") failed. Errno " << errno << " (" << strerror(errno) << ")");
485 // 224.0.0.0 - 239.255.255.255 are multicast
486 // Usage of 239.x.x.x is recommended for local scope
487 // Reference: http://tools.ietf.org/html/rfc5771
488 if( ntohl(addr.getIP()) >= 0xe0000000 && ntohl(addr.getIP()) <= 0xefffffff ) {
491 struct sockaddr_in a;
492 a.sin_addr.S_un.S_addr = INADDR_ANY;
493 a.sin_family = AF_INET;
494 a.sin_port = htons(port);
496 if( (result = ::bind(handle,(const sockaddr*)&a,sizeof(a))) < 0 ) {
497 SG_LOG(SG_IO, SG_ALERT, "bind(any:" << port << ") failed. Errno " << errno << " (" << strerror(errno) << ")");
503 mreq.imr_multiaddr.s_addr = addr.getIP();
504 mreq.imr_interface.s_addr = htonl(INADDR_ANY);
505 if( (result=::setsockopt(getHandle(), IPPROTO_IP, IP_ADD_MEMBERSHIP, (const char *)&mreq, sizeof(mreq))) != 0 ) {
506 SG_LOG(SG_IO, SG_ALERT, "setsockopt(IP_ADD_MEMBERSHIP) failed. Errno " << errno << " (" << strerror(errno) << ")");
511 else if( (result = ::bind(handle,addr.getAddr(), addr.getAddrLen())) < 0 ) {
512 SG_LOG(SG_IO, SG_ALERT, "bind(" << host << ":" << port << ") failed. Errno " << errno << " (" << strerror(errno) << ")");
521 int Socket::listen ( int backlog )
523 assert ( handle != -1 ) ;
524 return ::listen(handle,backlog);
528 int Socket::accept ( IPAddress* addr )
530 assert ( handle != -1 ) ;
534 return ::accept(handle,NULL,NULL);
538 socklen_t addr_len = addr->getAddrLen(); ;
539 return ::accept(handle, addr->getAddr(), &addr_len);
544 int Socket::connect ( const char* host, int port )
546 IPAddress addr ( host, port ) ;
547 return connect ( &addr );
551 int Socket::connect ( IPAddress* addr )
553 assert ( handle != -1 ) ;
554 if ( addr->getBroadcast() ) {
555 setBroadcast( true );
557 return ::connect(handle, addr->getAddr(), addr->getAddrLen() );
561 int Socket::send (const void * buffer, int size, int flags)
563 assert ( handle != -1 ) ;
564 return ::send (handle, (const char*)buffer, size, flags);
568 int Socket::sendto ( const void * buffer, int size,
569 int flags, const IPAddress* to )
571 assert ( handle != -1 ) ;
572 return ::sendto(handle,(const char*)buffer,size,flags,
573 (const sockaddr*) to->getAddr(), to->getAddrLen());
577 int Socket::recv (void * buffer, int size, int flags)
579 assert ( handle != -1 ) ;
580 return ::recv (handle, (char*)buffer, size, flags);
584 int Socket::recvfrom ( void * buffer, int size,
585 int flags, IPAddress* from )
587 assert ( handle != -1 ) ;
588 socklen_t fromlen = (socklen_t) from->getAddrLen() ;
589 return ::recvfrom(handle,(char*)buffer,size,flags, from->getAddr(),&fromlen);
593 void Socket::close (void)
598 ::closesocket( handle );
607 bool Socket::isNonBlockingError ()
610 int wsa_errno = WSAGetLastError();
611 if ( wsa_errno != 0 )
614 SG_LOG(SG_IO, SG_WARN, "isNonBlockingError: WSAGetLastError():" << wsa_errno);
616 case WSAEWOULDBLOCK: // always == NET_EAGAIN?
625 case EWOULDBLOCK: // always == NET_EAGAIN?
636 //////////////////////////////////////////////////////////////////////
638 // modified version by os
640 //////////////////////////////////////////////////////////////////////
641 int Socket::select ( Socket** reads, Socket** writes, int timeout )
654 for ( i=0; reads[i]; i++ )
656 int fd = reads[i]->getHandle();
664 for ( i=0; writes[i]; i++ )
666 int fd = writes[i]->getHandle();
675 /* Set up the timeout */
677 tv.tv_sec = timeout/1000;
678 tv.tv_usec = (timeout%1000)*1000;
680 // It bothers me that select()'s first argument does not appear to
681 // work as advertised... [it hangs like this if called with
682 // anything less than FD_SETSIZE, which seems wasteful?]
684 // Note: we ignore the 'exception' fd_set - I have never had a
685 // need to use it. The name is somewhat misleading - the only
686 // thing I have ever seen it used for is to detect urgent data -
687 // which is an unportable feature anyway.
689 retval = ::select (FD_SETSIZE, &r, &w, 0, &tv);
691 //remove sockets that had no activity
697 for ( k=i=0; reads[i]; i++ )
699 int fd = reads[i]->getHandle();
700 if ( FD_ISSET (fd, &r) )
702 reads[k++] = reads[i];
711 for ( k=i=0; writes[i]; i++ )
713 int fd = writes[i]->getHandle();
714 if ( FD_ISSET (fd, &w) )
716 writes[k++] = writes[i];
723 if (retval == 0) // timeout
725 if (retval == -1)// error
732 /* Init/Exit functions */
734 static void netExit ( void )
737 /* Clean up windows networking */
738 if ( WSACleanup() == SOCKET_ERROR ) {
739 if ( WSAGetLastError() == WSAEINPROGRESS ) {
740 WSACancelBlockingCall();
747 int Socket::initSockets()
750 /* Start up the windows networking */
751 WORD version_wanted = MAKEWORD(1,1);
754 if ( WSAStartup(version_wanted, &wsaData) != 0 ) {
755 throw sg_exception("WinSock initialization failed");
764 } // of namespace simgear