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>
29 #include "sg_socket.hxx"
31 #if defined(_WIN32) && !defined(__CYGWIN__)
32 # define WINSOCK // use winsock convetions, otherwise standard POSIX
39 #include <cstdio> // for snprintf
45 # include <sys/types.h>
46 # include <sys/socket.h>
47 # include <netinet/in.h>
48 # include <arpa/inet.h>
49 # include <sys/time.h>
55 #if defined(_MSC_VER) && !defined(socklen_t)
59 #include <simgear/debug/logstream.hxx>
60 #include <simgear/structure/exception.hxx>
65 IPAddress::IPAddress ( const char* host, int port )
71 void IPAddress::set ( const char* host, int port )
73 memset(this, 0, sizeof(IPAddress));
75 sin_family = AF_INET ;
76 sin_port = htons (port);
78 /* Convert a string specifying a host name or one of a few symbolic
79 ** names to a numeric IP address. This usually calls gethostbyname()
80 ** to do the work; the names "" and "<broadcast>" are special.
83 if (!host || host[0] == '\0') {
84 sin_addr = INADDR_ANY;
88 if (strcmp(host, "<broadcast>") == 0) {
89 sin_addr = INADDR_BROADCAST;
93 sin_addr = inet_addr ( host ) ;
94 if (sin_addr != INADDR_NONE) {
97 // finally, try gethostbyname
98 struct hostent *hp = gethostbyname ( host ) ;
100 SG_LOG(SG_IO, SG_WARN, "gethostbyname failed for " << host);
101 sin_addr = INADDR_ANY ;
105 memcpy ( (char *) &sin_addr, hp->h_addr, hp->h_length ) ;
109 /* Create a string object representing an IP address.
110 This is always a string of the form 'dd.dd.dd.dd' (with variable
113 const char* IPAddress::getHost () const
116 const char* buf = inet_ntoa ( sin_addr ) ;
118 static char buf [32];
119 long x = ntohl(sin_addr);
120 sprintf(buf, "%d.%d.%d.%d",
121 (int) (x>>24) & 0xff, (int) (x>>16) & 0xff,
122 (int) (x>> 8) & 0xff, (int) (x>> 0) & 0xff );
127 unsigned int IPAddress::getIP () const
132 unsigned int IPAddress::getPort() const
134 return ntohs(sin_port);
137 unsigned int IPAddress::getFamily () const
142 const char* IPAddress::getLocalHost ()
144 //gethostbyname(gethostname())
147 memset(buf, 0, sizeof(buf));
148 gethostname(buf, sizeof(buf)-1);
149 const hostent *hp = gethostbyname(buf);
151 if (hp && *hp->h_addr_list)
153 in_addr addr = *((in_addr*)*hp->h_addr_list);
154 const char* host = inet_ntoa(addr);
164 bool IPAddress::getBroadcast () const
166 return sin_addr == INADDR_BROADCAST;
182 void Socket::setHandle (int _handle)
189 bool Socket::open ( bool stream )
192 handle = ::socket ( AF_INET, (stream? SOCK_STREAM: SOCK_DGRAM), 0 ) ;
194 // Jan 26, 2010: Patch to avoid the problem of the socket resource not
195 // yet being available if the program is restarted quickly after being
198 // Reference: http://www.unixguide.net/network/socketfaq/4.5.shtml
200 // Also required for joining multicast domains
203 #if defined(_WIN32) || defined(__CYGWIN__)
204 setsockopt( handle, SOL_SOCKET, SO_REUSEADDR, (char *)&opt_boolean,
205 sizeof(opt_boolean) );
207 setsockopt( handle, SOL_SOCKET, SO_REUSEADDR, &opt_boolean,
208 sizeof(opt_boolean) );
212 return (handle != -1);
216 void Socket::setBlocking ( bool blocking )
218 assert ( handle != -1 ) ;
221 u_long nblocking = blocking? 0: 1;
222 ::ioctlsocket(handle, FIONBIO, &nblocking);
225 int delay_flag = ::fcntl (handle, F_GETFL, 0);
228 delay_flag &= (~O_NDELAY);
230 delay_flag |= O_NDELAY;
232 ::fcntl (handle, F_SETFL, delay_flag);
237 void Socket::setBroadcast ( bool broadcast )
239 assert ( handle != -1 ) ;
243 #if defined(_WIN32) || defined(__CYGWIN__)
244 result = ::setsockopt( handle, SOL_SOCKET, SO_BROADCAST, (char*)&one, sizeof(one) );
246 result = ::setsockopt( handle, SOL_SOCKET, SO_BROADCAST, &one, sizeof(one) );
249 result = ::setsockopt( handle, SOL_SOCKET, SO_BROADCAST, NULL, 0 );
253 throw sg_exception("Socket::setBroadcast failed");
258 int Socket::bind ( const char* host, int port )
261 assert ( handle != -1 ) ;
262 IPAddress addr ( host, port ) ;
263 if( (result = ::bind(handle,(const sockaddr*)&addr,sizeof(IPAddress))) < 0 ) {
264 SG_LOG(SG_IO, SG_ALERT, "bind(" << host << ":" << port << ") failed. Errno " << errno << " (" << strerror(errno) << ")");
268 // 224.0.0.0 - 239.255.255.255 are multicast
269 // Usage of 239.x.x.x is recommended for local scope
270 // Reference: http://tools.ietf.org/html/rfc5771
271 if( ntohl(addr.getIP()) >= 0xe0000000 && ntohl(addr.getIP()) <= 0xefffffff ) {
273 mreq.imr_multiaddr.s_addr = addr.getIP();
274 mreq.imr_interface.s_addr = htonl(INADDR_ANY);
275 if( (result=::setsockopt(getHandle(), IPPROTO_IP, IP_ADD_MEMBERSHIP, (const char *)&mreq, sizeof(mreq))) != 0 ) {
276 SG_LOG(SG_IO, SG_ALERT, "setsockopt(IP_ADD_MEMBERSHIP) failed. Errno " << errno << " (" << strerror(errno) << ")");
285 int Socket::listen ( int backlog )
287 assert ( handle != -1 ) ;
288 return ::listen(handle,backlog);
292 int Socket::accept ( IPAddress* addr )
294 assert ( handle != -1 ) ;
298 return ::accept(handle,NULL,NULL);
302 socklen_t addr_len = (socklen_t) sizeof(IPAddress) ;
303 return ::accept(handle,(sockaddr*)addr,&addr_len);
308 int Socket::connect ( const char* host, int port )
310 assert ( handle != -1 ) ;
311 IPAddress addr ( host, port ) ;
312 if ( addr.getBroadcast() ) {
313 setBroadcast( true );
315 return ::connect(handle,(const sockaddr*)&addr,sizeof(IPAddress));
319 int Socket::send (const void * buffer, int size, int flags)
321 assert ( handle != -1 ) ;
322 return ::send (handle, (const char*)buffer, size, flags);
326 int Socket::sendto ( const void * buffer, int size,
327 int flags, const IPAddress* to )
329 assert ( handle != -1 ) ;
330 return ::sendto(handle,(const char*)buffer,size,flags,
331 (const sockaddr*)to,sizeof(IPAddress));
335 int Socket::recv (void * buffer, int size, int flags)
337 assert ( handle != -1 ) ;
338 return ::recv (handle, (char*)buffer, size, flags);
342 int Socket::recvfrom ( void * buffer, int size,
343 int flags, IPAddress* from )
345 assert ( handle != -1 ) ;
346 socklen_t fromlen = (socklen_t) sizeof(IPAddress) ;
347 return ::recvfrom(handle,(char*)buffer,size,flags,(sockaddr*)from,&fromlen);
351 void Socket::close (void)
356 ::closesocket( handle );
365 bool Socket::isNonBlockingError ()
368 int wsa_errno = WSAGetLastError();
369 if ( wsa_errno != 0 )
372 SG_LOG(SG_IO, SG_WARN, "isNonBlockingError: WSAGetLastError():" << wsa_errno);
374 case WSAEWOULDBLOCK: // always == NET_EAGAIN?
383 case EWOULDBLOCK: // always == NET_EAGAIN?
394 //////////////////////////////////////////////////////////////////////
396 // modified version by os
398 //////////////////////////////////////////////////////////////////////
399 int Socket::select ( Socket** reads, Socket** writes, int timeout )
412 for ( i=0; reads[i]; i++ )
414 int fd = reads[i]->getHandle();
422 for ( i=0; writes[i]; i++ )
424 int fd = writes[i]->getHandle();
433 /* Set up the timeout */
435 tv.tv_sec = timeout/1000;
436 tv.tv_usec = (timeout%1000)*1000;
438 // It bothers me that select()'s first argument does not appear to
439 // work as advertised... [it hangs like this if called with
440 // anything less than FD_SETSIZE, which seems wasteful?]
442 // Note: we ignore the 'exception' fd_set - I have never had a
443 // need to use it. The name is somewhat misleading - the only
444 // thing I have ever seen it used for is to detect urgent data -
445 // which is an unportable feature anyway.
447 retval = ::select (FD_SETSIZE, &r, &w, 0, &tv);
449 //remove sockets that had no activity
455 for ( k=i=0; reads[i]; i++ )
457 int fd = reads[i]->getHandle();
458 if ( FD_ISSET (fd, &r) )
460 reads[k++] = reads[i];
469 for ( k=i=0; writes[i]; i++ )
471 int fd = writes[i]->getHandle();
472 if ( FD_ISSET (fd, &w) )
474 writes[k++] = writes[i];
481 if (retval == 0) // timeout
483 if (retval == -1)// error
490 /* Init/Exit functions */
492 static void netExit ( void )
495 /* Clean up windows networking */
496 if ( WSACleanup() == SOCKET_ERROR ) {
497 if ( WSAGetLastError() == WSAEINPROGRESS ) {
498 WSACancelBlockingCall();
505 int Socket::initSockets()
507 assert ( sizeof(sockaddr_in) == sizeof(IPAddress) ) ;
510 /* Start up the windows networking */
511 WORD version_wanted = MAKEWORD(1,1);
514 if ( WSAStartup(version_wanted, &wsaData) != 0 ) {
515 throw sg_exception("WinSock initialization failed");
524 } // of namespace simgear