-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.c
67 lines (56 loc) · 1.69 KB
/
server.c
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
59
60
61
62
63
64
65
66
67
//
// Create a socket to serve the http server on
//
#include <winsock2.h>
#include "server.h"
void initialize_winsock() {
WSADATA wsaData;
int result = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (result != 0) {
printf("WSAStartup failed: %d\n", result);
exit(1);
}
}
SOCKET create_socket() {
SOCKET server_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (server_socket == INVALID_SOCKET) {
printf("Socket creation failed: %ld\n", WSAGetLastError());
WSACleanup();
exit(1);
}
return server_socket;
}
void bind_socket(SOCKET server_socket) {
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(PORT);
int result = bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr));
if (result == SOCKET_ERROR) {
printf("Bind failed: %ld\n", WSAGetLastError());
closesocket(server_socket);
WSACleanup();
exit(1);
}
}
void listen_for_connections(SOCKET server_socket) {
int result = listen(server_socket, SOMAXCONN);
if (result == SOCKET_ERROR) {
printf("Listen failed: %ld\n", WSAGetLastError());
closesocket(server_socket);
WSACleanup();
exit(1);
}
}
SOCKET accept_connection(SOCKET server_socket) {
/* accept() blocks until it has something to "accept" */
SOCKET client_socket = accept(server_socket, NULL, NULL);
if (client_socket == INVALID_SOCKET) {
printf("Accept failed: %ld\n", WSAGetLastError());
}
return client_socket;
}
void cleanup(SOCKET server_socket) {
closesocket(server_socket);
WSACleanup();
}