-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhttp-server.c
120 lines (96 loc) · 2.02 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <signal.h>
#include <fcntl.h>
#include "response.h"
int PORT = 8383;
char *ROOT;
int main(int argc, char **argv)
{
int sock_fd, clientfd;
struct sockaddr_in address;
socklen_t addrlen;
int buffsize = 1024;
char *buffer = malloc(buffsize);
char index[] = "index.html";
char html[] = ".html";
ROOT = getenv("PWD");
if ((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) > 0)
{
printf("Socket Created!\n");
}
else
{
perror("server: socket");
exit(1);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
if (bind(sock_fd, (struct sockaddr *)&address, sizeof(address)) == 0)
{
printf("Binding Socket!\n");
}
else
{
perror("server: bind");
exit(1);
}
while (1)
{
if (listen(sock_fd, 100) < 0)
{
perror("server: listen");
exit(1);
}
if ((clientfd = accept(sock_fd, (struct sockaddr *)&address, &addrlen)) < 0)
{
perror("server: accept");
exit(1);
}
if (clientfd > 0)
{
printf("Client Connected!\n");
}
recv(clientfd, buffer, buffsize, 0);
printf("%s\n", buffer);
char **tokens = malloc(100);
int split = 0;
char *token;
token = strtok(buffer, " \n");
while (split <= 2)
{
tokens[split] = token;
token = strtok(NULL, " \n");
split++;
}
char *METHOD = tokens[0];
char *PATH = tokens[1];
char final_path[1000] = "";
strcpy(final_path, ROOT);
strcat(final_path, PATH);
if (final_path[strlen(final_path) - 1] == '/')
{
strcat(final_path, index);
}
printf("File: %s\n", final_path);
int responseCode = get_response_code(METHOD, final_path);
printf("%d\n", responseCode);
response(clientfd, responseCode);
response_body(clientfd, final_path, responseCode);
close(clientfd);
}
close(sock_fd);
return 0;
}