-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.c
100 lines (81 loc) · 2.18 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
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
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
int main()
{
char message[10][150],buffer[150];
int i=0;
int clientSocket;
FILE *file_in;
file_in=fopen("config.txt", "r");
/*stores and prints the data from the string*/
while(fgets(buffer,150,file_in)){
strcpy(message[i],buffer);
// printf("%s",message[i]);
i++;
}
char *delim = ":";
unsigned count = 0;
char Port[100],Dir[100];
char *token =strtok(message,delim);
count++;
strcpy(Port,token);
token = strtok(NULL,delim);
strcpy(Port,token);
token = strtok(NULL,delim);
token = strtok(NULL,delim);
strcpy(Dir,token);
int PORT=atoi(Port);
fclose(file_in);
int server_fd, new_socket, valread;
char httpHeader[8000] = "HTTP/1.1 200 OK\nContent-Type:text/html\nContent-Length: 1000\n\n";
FILE *htmlData = fopen("index.html","r");
char line[100];
char responseData[8000];
while (fgets(line, 100, htmlData) != 0) {
strcat(responseData, line);
}
// char httpHeader[8000] = "HTTP/1.1 200 OK\r\n\n";
strcat(httpHeader, responseData);
struct sockaddr_in address;
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
{
perror("In socket");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
if (bind(server_fd, (struct sockaddr *)&address,
sizeof(address) ) <0)
{
perror("In bind");
exit(EXIT_FAILURE);
}
if (listen(server_fd, 10) < 0)
{
perror("In listen");
exit(EXIT_FAILURE);
}
int addrlen = sizeof(address);
while(1) // infinite while loop for accepting request of different clients
{
if ((new_socket = accept(server_fd, (struct sockaddr *)&address,
(socklen_t*)&addrlen))<0)
{
perror("In accept");
exit(EXIT_FAILURE);
}
char buffer[30000] = {0};
valread = read( new_socket , buffer, 30000);
printf("%s\n",buffer );
//setHttpHeader(httpHeader,Dir); // Custom function to set header
write(new_socket ,httpHeader,sizeof(httpHeader));
printf("-------Response sent to client---------\n");
close(new_socket);
}
return 0;
}