forked from JeffreytheCoder/Simple-HTTP-Server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.c
More file actions
executable file
·87 lines (70 loc) · 1.98 KB
/
main.c
File metadata and controls
executable file
·87 lines (70 loc) · 1.98 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
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
79
80
81
82
83
84
85
86
87
#include "file.h"
#include "compare.h"
#include "http.h"
#include "server.h"
#include <arpa/inet.h>
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <pthread.h>
#include <regex.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int port;
if (argc < 2) {
fprintf(stderr, "Usage %s <port>\n", argv[0]);
}
port = atoi(argv[1]);
int server_fd;
struct sockaddr_in server_addr;
// create server socket
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// config socket
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(port);
// bind socket to port
if (bind(server_fd,
(struct sockaddr *)&server_addr,
sizeof(server_addr)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// listen for connections
if (listen(server_fd, 10) < 0) {
perror("listen failed");
exit(EXIT_FAILURE);
}
printf("Server listening on port %d\n", port);
while (1) {
// client info
struct sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
int *client_fd = malloc(sizeof(int));
// accept client connection
if ((*client_fd = accept(server_fd,
(struct sockaddr *)&client_addr,
&client_addr_len)) < 0) {
perror("accept failed");
continue;
}
// create a new thread to handle client request
pthread_t thread_id;
pthread_create(&thread_id, NULL, handle_client, (void *)client_fd);
pthread_detach(thread_id);
}
close(server_fd);
return 0;
}