medfall

A super great game engine
Log | Files | Refs

unix_network.cc (1572B)


      1 #include <arpa/inet.h>
      2 #include <sys/types.h>
      3 #include <sys/select.h>
      4 #include <sys/socket.h>
      5 #include <errno.h>
      6 #include <fcntl.h>
      7 #include <netdb.h>
      8 #include <unistd.h>
      9 
     10 #define INVALID_SOCKET ( -1 )
     11 #define SOCKET_ERROR ( -1 )
     12 
     13 #define closesocket close
     14 
     15 #if PLATFORM_OSX
     16 static int NET_SEND_FLAGS = 0;
     17 #else
     18 static int NET_SEND_FLAGS = MSG_NOSIGNAL;
     19 #endif
     20 
     21 void net_init() { }
     22 void net_term() { }
     23 
     24 static void make_socket_nonblocking( int fd ) {
     25 	int flags = fcntl( fd, F_GETFL, 0 );
     26 	if( flags == -1 ) FATAL( "fcntl F_GETFL" );
     27 	int ok = fcntl( fd, F_SETFL, flags | O_NONBLOCK );
     28 	if( ok == -1 ) FATAL( "fcntl F_SETFL" );
     29 }
     30 
     31 static void platform_init_sock( int fd ) {
     32 #if PLATFORM_OSX
     33 	setsockoptone( fd, SOL_SOCKET, SO_NOSIGPIPE );
     34 #endif
     35 }
     36 
     37 bool net_tryrecv( UDPSocket sock, void * buf, size_t len, NetAddress * addr, size_t * bytes_received ) {
     38 	struct sockaddr_storage sa;
     39 
     40 	socklen_t sa_size = sizeof( struct sockaddr_in );
     41 	ssize_t received4 = recvfrom( sock.ipv4, buf, len, 0, ( struct sockaddr * ) &sa, &sa_size );
     42 	if( received4 != -1 ) {
     43 		*addr = sockaddr_to_netaddress( sa );
     44 		*bytes_received = size_t( received4 );
     45 		return true;
     46 	}
     47 	if( received4 == -1 && errno != EAGAIN ) {
     48 		FATAL( "recvfrom" );
     49 	}
     50 
     51 	sa_size = sizeof( struct sockaddr_in6 );
     52 	ssize_t received6 = recvfrom( sock.ipv6, buf, len, 0, ( struct sockaddr * ) &sa, &sa_size );
     53 	if( received6 != -1 ) {
     54 		*addr = sockaddr_to_netaddress( sa );
     55 		*bytes_received = size_t( received6 );
     56 		return true;
     57 	}
     58 	if( received6 == -1 && errno != EAGAIN ) {
     59 		FATAL( "recvfrom" );
     60 	}
     61 
     62 	return false;
     63 }