-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHTTP_Server.c
More file actions
97 lines (77 loc) · 2.58 KB
/
Copy pathHTTP_Server.c
File metadata and controls
97 lines (77 loc) · 2.58 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
88
89
90
91
92
93
94
95
96
97
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <pthread.h>
#define PORT 8080
void *connection_handler(void *socket_desc) {
int sock = *(int*)socket_desc;
char buffer[1024];
char method[16];
char URL[1024];
char protocol[16];
char *hello = "HTTP/1.1 200 OK\nContent-Type: text/html\nContent-Length: 12\n\nHello, world!";
char temp_string[strlen(hello)];
char s2[]="\n\n";
for (int i = 0; i < strlen(hello) ;i++){
temp_string[i]=hello[i];
}
read(sock,buffer,1024);
printf("HTTP receieved: %s\n",buffer);
sscanf(buffer,"%s %s %s",method,URL,protocol);
printf("Method: %s\n",method);
printf("URL: %s\n",URL);
printf("Protocol: %s\n",protocol);
char *message;
char* p = strstr(temp_string,s2);
if (p){
strcpy(p,"");
}
asprintf(&message,"%s\nMethod: %s\nURL: %s\nProtocol: %s\n\n%s",temp_string,method,URL,protocol,hello+strlen(temp_string));
printf("message: %s\n",message);
write(sock, message, strlen(message));
printf("Response sent\n");
close(sock);
free(socket_desc);
free(message);
return NULL;
}
int main() {
int server_fd, new_socket, *new_sock;
struct sockaddr_in address;
int addrlen = sizeof(address);
// Creating socket file descriptor
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( PORT );
// Forcefully attaching socket to the port 8080
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address))<0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
if (listen(server_fd, 3) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
while(1) {
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0) {
perror("accept");
exit(EXIT_FAILURE);
}
pthread_t thread;
new_sock = malloc(sizeof(int));
*new_sock = new_socket;
if (pthread_create(&thread, NULL, connection_handler, (void*)new_sock) < 0) {
perror("could not create thread");
exit(EXIT_FAILURE);
}
// Detach the thread so it doesn't need to be joined
pthread_detach(thread);
}
return 0;
}