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
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define MAX_CLIENTS 2
#define MAX_RESPONSE_SIZE 1024
#define DEFAULT_PORT 8081
int main()
{
struct sockaddr_in server;
struct sockaddr_in client;
int sock;
int new_accepted;
int sockaddr_sizeof = sizeof( struct sockaddr_in );
ssize_t data_len;
char response[MAX_RESPONSE_SIZE];
if( (sock = socket(AF_INET, SOCK_STREAM,0)) == -1 )
{
perror("couldnot create socket");
exit(1);
}
server.sin_family = AF_INET;
server.sin_port = htons( DEFAULT_PORT );
server.sin_addr.s_addr = INADDR_ANY;
bzero(&server.sin_zero, 8);
if ( bind( sock, (struct sockaddr *)&server, sockaddr_sizeof ) == -1 )
{
perror("Cannot bind");
exit(1);
}
if ( listen( sock, MAX_CLIENTS ) == -1 )
{
perror("Error while listening");
exit(1);
}
while ( 1 != 2 )
{
if ((new_accepted = accept(sock, (struct sockaddr *)&client, &sockaddr_sizeof )) == -1)
{
perror("could not accept new connection");
exit(1);
}
printf("New Client connected from port no %d and IP %s\n", ntohs(client.sin_port), inet_ntoa(client.sin_addr));
data_len = 1;
while( data_len )
{
data_len = recv( new_accepted, response, MAX_RESPONSE_SIZE-1, 0 );
response[data_len-1]=0;
printf("Http-request size: %d byte\n", data_len);
printf("%s", response);
if ( data_len )
{
//char *p = (char *)memchr(&response[4], ' ', strlen( &response[4] ) );
//*p = '\0';
//send( new_accepted, &response[4], p-&response[4], 0 );
send( new_accepted, "\r\n", 2, 0 );
//send( new_accepted, response, data_len, 0 );
//send( new_accepted, "Hello", 5, 0 );
send( new_accepted, response, data_len-1, 0 );
data_len = 0;
}
}
printf("Client disconnected\n");
close( new_accepted );
}
close( sock );
return 0;
}
|