medfall

A super great game engine
Log | Files | Refs

win32_network.cc (1509B)


      1 #include <winsock2.h>
      2 #include <ws2tcpip.h>
      3 
      4 static int NET_SEND_FLAGS = 0;
      5 
      6 void net_init() {
      7 	WSADATA wsa_data;
      8 	if( WSAStartup( MAKEWORD( 2, 2 ), &wsa_data ) == SOCKET_ERROR ) {
      9 		FATAL( "WSAStartup" );
     10 	}
     11 }
     12 
     13 void net_term() {
     14 	if( WSACleanup() == SOCKET_ERROR ) {
     15 		FATAL( "WSACleanup" );
     16 	}
     17 }
     18 
     19 static void make_socket_nonblocking( SOCKET fd ) {
     20 	u_long one = 1;
     21 	int ok = ioctlsocket( fd, FIONBIO, &one );
     22 	if( ok == SOCKET_ERROR ) {
     23 		FATAL( "ioctlsocket" );
     24 	}
     25 }
     26 
     27 static void platform_init_sock( SOCKET fd ) { }
     28 
     29 bool net_tryrecv( UDPSocket sock, void * buf, size_t len, NetAddress * addr, size_t * bytes_received ) {
     30 	struct sockaddr_storage sa;
     31 
     32 	socklen_t sa_size = sizeof( struct sockaddr_in );
     33 	ssize_t received4 = recvfrom( sock.ipv4, ( char * ) buf, len, 0, ( struct sockaddr * ) &sa, &sa_size );
     34 	if( received4 != SOCKET_ERROR ) {
     35 		*addr = sockaddr_to_netaddress( sa );
     36 		*bytes_received = size_t( received4 );
     37 		return true;
     38 	}
     39 	else {
     40 		int error = WSAGetLastError();
     41 		if( error != WSAEWOULDBLOCK && error != WSAECONNRESET ) {
     42 			FATAL( "recvfrom" );
     43 		}
     44 	}
     45 
     46 	sa_size = sizeof( struct sockaddr_in6 );
     47 	ssize_t received6 = recvfrom( sock.ipv6, ( char * ) buf, len, 0, ( struct sockaddr * ) &sa, &sa_size );
     48 	if( received6 != SOCKET_ERROR ) {
     49 		*addr = sockaddr_to_netaddress( sa );
     50 		*bytes_received = size_t( received6 );
     51 		return true;
     52 	}
     53 	else {
     54 		int error = WSAGetLastError();
     55 		if( error != WSAEWOULDBLOCK && error != WSAECONNRESET ) {
     56 			FATAL( "recvfrom" );
     57 		}
     58 	}
     59 
     60 	return false;
     61 }