#include #include #include #include #include #include #include #include #include #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; }