forked from ucsd-cse29/lab5-starter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http-server.c
80 lines (61 loc) · 2.27 KB
/
http-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
68
69
70
71
72
73
74
75
76
77
78
#include "http-server.h"
void start_server(void(*handler)(char*, int), int port) {
int server_sock, client_sock;
struct sockaddr_in server_addr, client_addr;
socklen_t client_len = sizeof(client_addr);
// Create a socket
if ((server_sock = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// Allow the port to be reused (fixes "bind failed: Address already in use")
int enable = 1;
if (setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0)
perror("setsockopt(SO_REUSEADDR) failed");
if (setsockopt(server_sock, SOL_SOCKET, SO_REUSEPORT, &enable, sizeof(int)) < 0)
perror("setsockopt(SO_REUSEPORT) failed");
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(port);
socklen_t addr_len = sizeof(server_addr);
if (bind(server_sock, (struct sockaddr *)&server_addr, addr_len) < 0) {
perror("bind failed");
close(server_sock);
exit(EXIT_FAILURE);
}
// Listen for incoming connections
if (listen(server_sock, 10) < 0) {
perror("listen failed");
close(server_sock);
exit(EXIT_FAILURE);
}
// get port number
if (getsockname(server_sock, (struct sockaddr *)&server_addr, &addr_len) == -1) {
perror("getsockname failed");
exit(EXIT_FAILURE);
}
printf("Server started on port %d\n", ntohs(server_addr.sin_port));
char buffer[BUFFER_SIZE];
// Main server loop
while (1) {
if ((client_sock = accept(server_sock, (struct sockaddr *)&client_addr, &client_len)) < 0) {
perror("accept failed");
close(server_sock);
exit(EXIT_FAILURE);
}
// Receive the request
int num_read = recv(client_sock, buffer, BUFFER_SIZE - 1, 0);
if(num_read < 0) {
perror("recv failed");
close(client_sock);
close(server_sock);
exit(EXIT_FAILURE);
}
assert(num_read <= BUFFER_SIZE - 1);
buffer[num_read] = '\0';
(*handler)(buffer, client_sock);
// Close the connection with the client
close(client_sock);
}
close(server_sock);
}