all repos — mgba @ c5d243fca282cf11d7f2c38010fce18361babdc2

mGBA Game Boy Advance Emulator

src/util/socket.h (view raw)

 1#ifndef SOCKET_H
 2#define SOCKET_H
 3
 4#ifdef _WIN32
 5#include <winsock2.h>
 6
 7typedef SOCKET Socket;
 8#else
 9#include <fcntl.h>
10#include <netinet/in.h>
11#include <netinet/tcp.h>
12#include <stdio.h>
13#include <sys/socket.h>
14#include <unistd.h>
15
16typedef int Socket;
17#endif
18
19
20static inline void SocketSubsystemInitialize() {
21#ifdef _WIN32
22	WSAStartup(MAKEWORD(2, 2), 0);
23#endif
24}
25
26static inline ssize_t SocketSend(Socket socket, const void* buffer, size_t size) {
27	return write(socket, buffer, size);
28}
29
30static inline ssize_t SocketRecv(Socket socket, void* buffer, size_t size) {
31	return read(socket, buffer, size);
32}
33
34static inline Socket SocketOpenTCP(int port, uint32_t bindAddress) {
35	Socket sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
36	if (sock < 0) {
37		return sock;
38	}
39
40	struct sockaddr_in bindInfo = {
41		.sin_family = AF_INET,
42		.sin_port = htons(port),
43		.sin_addr = {
44			.s_addr = htonl(bindAddress)
45		}
46	};
47	int err = bind(sock, (const struct sockaddr*) &bindInfo, sizeof(struct sockaddr_in));
48	if (err) {
49		close(sock);
50		return -1;
51	}
52	return sock;
53}
54
55static inline Socket SocketListen(Socket socket, int queueLength) {
56	return listen(socket, queueLength);
57}
58
59static inline Socket SocketAccept(Socket socket, struct sockaddr* restrict address, socklen_t* restrict addressLength) {
60	return accept(socket, address, addressLength);
61}
62
63static inline int SocketClose(Socket socket) {
64	return close(socket) >= 0;
65}
66
67static inline int SocketSetBlocking(Socket socket, int blocking) {
68#ifdef _WIN32
69	blocking = !blocking;
70	return ioctlsocket(socket, FIONBIO, &blocking) == NO_ERROR;
71#else
72	int flags = fcntl(socket, F_GETFL);
73	if (flags == -1) {
74		return 0;
75	}
76	if (blocking) {
77		flags &= ~O_NONBLOCK;
78	} else {
79		flags |= O_NONBLOCK;
80	}
81	return fcntl(socket, F_SETFL, flags) >= 0;
82#endif
83}
84
85static inline int SocketSetTCPPush(Socket socket, int push) {
86	return setsockopt(socket, IPPROTO_TCP, TCP_NODELAY, (char*) &push, sizeof(int)) >= 0;
87}
88
89#endif