medfall

A super great game engine
Log | Files | Refs

unix_network.h (1451B)


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
48
49
50
51
52
53
54
55
56
57
58
#pragma once

#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <unistd.h>

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

#define INVALID_SOCKET ( -1 )
#define SOCKET_ERROR ( -1 )

#define closesocket close

inline void net_init() { }
inline void net_term() { }

inline void sock_fd_nonblocking( int fd ) {
	int flags = fcntl( fd, F_GETFL, 0 );
	if( flags == -1 ) FATAL( "fcntl F_GETFL" );
	int ok = fcntl( fd, F_SETFL, flags | O_NONBLOCK );
	if( ok == -1 ) FATAL( "fcntl F_SETFL" );
}

inline bool net_tryrecv( UDPSocket sock, void * buf, size_t len, NetAddress * addr, size_t * bytes_received ) {
	struct sockaddr_storage sa;
	socklen_t sa_size = sizeof( struct sockaddr_in );
	ssize_t received4 = recvfrom( sock.ipv4, buf, len, 0, ( struct sockaddr * ) &sa, &sa_size );
	if( received4 != -1 ) {
		*addr = sockaddr_to_netaddress( sa );
		*bytes_received = size_t( received4 );
		return true;
	}
	if( received4 == -1 && errno != EAGAIN ) {
		FATAL( "recvfrom" );
	}

	sa_size = sizeof( struct sockaddr_in6 );
	ssize_t received6 = recvfrom( sock.ipv6, buf, len, 0, ( struct sockaddr * ) &sa, &sa_size );
	if( received6 != -1 ) {
		*addr = sockaddr_to_netaddress( sa );
		*bytes_received = size_t( received6 );
		return true;
	}
	if( received6 == -1 && errno != EAGAIN ) {
		FATAL( "recvfrom" );
	}

	return false;
}