-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocket_util.h
More file actions
52 lines (46 loc) · 1.28 KB
/
socket_util.h
File metadata and controls
52 lines (46 loc) · 1.28 KB
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
#ifndef SOCKET_UTIL_H
#define SOCKET_UTIL_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
#define SOCKET_T SOCKET
#define CLOSE_SOCKET(s) closesocket(s)
#define SOCKET_ERROR_VAL SOCKET_ERROR
#else
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/select.h>
#include <sys/time.h>
#define SOCKET_T int
#define CLOSE_SOCKET(s) close(s)
#define SOCKET_ERROR_VAL -1
#define INVALID_SOCKET -1
#ifndef max
#define max(a,b) ((a) > (b) ? (a) : (b))
#endif
#endif
static inline SOCKET_T tcp_socket_create(void) {
SOCKET_T sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == SOCKET_ERROR_VAL) {
perror("socket create failed");
return SOCKET_ERROR_VAL;
}
return sock;
}
static inline int socket_set_reuseaddr(SOCKET_T sock) {
int opt = 1;
return setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const void*)&opt, sizeof(opt));
}
#ifdef _WIN32
static inline int winsock_init(void) {
WSADATA wsaData;
return WSAStartup(MAKEWORD(2, 2), &wsaData);
}
#endif
#endif // SOCKET_UTIL_H