all repos — mgba @ 20a5fa8476993eb5ca89b3d974641f65489b8dfa

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