medfall

A super great game engine
Log | Files | Refs

win32_network.h (1052B)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#pragma once

#include <winsock2.h>
#include <ws2tcpip.h>

struct Socket {
	SOCKET fd;
	TransportProtocol transport;
	IPvX ipvx;
};

inline void net_init() {
	WSADATA wsa_data;
	if( WSAStartup( MAKEWORD( 2, 2 ), &wsa_data ) == SOCKET_ERROR ) {
		FATAL( "WSAStartup" );
	}
}

inline void net_term() {
	if( WSACleanup() == SOCKET_ERROR ) {
		FATAL( "WSACleanup" );
	}
}

inline void sock_fd_nonblocking( SOCKET fd ) {
	u_long one = 1;
	int ok = ioctlsocket( fd, FIONBIO, &one );
	if( ok == SOCKET_ERROR ) {
		FATAL( "ioctlsocket" );
	}
}

inline bool sock_tryrecv_udp( Socket sock, char * buf, size_t len, sockaddr_storage * addr, socklen_t * addr_len, size_t * bytes_received ) {
	ASSERT( sock.transport == NET_UDP );

	int received = recvfrom( sock.fd, buf, checked_cast< int >( len ), 0, ( sockaddr * ) addr, addr_len );
	if( received == SOCKET_ERROR ) {
		int error = WSAGetLastError();
		if( error == WSAEWOULDBLOCK || error == WSAECONNRESET ) {
			return false;
		}
		FATAL( "recvfrom" );
	}

	*bytes_received = size_t( received );
	return true;
}