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
|
void *connect_server(void *);
int main(int argc , char *argv[]) { int socket_desc , new_socket , c,*new_sock; struct sockaddr_in server , client; char *message;
//Create socket socket_desc = socket(AF_INET , SOCK_STREAM , 0); if (socket_desc == -1) { printf("Could not create socket"); }
//Prepare the sockaddr_in structure server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons( 5555 );
//Bind if(bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0) { puts("bind failed"); return 1; } puts("bind done");
//Listen listen(socket_desc , 3);
//Accept and incoming connection puts("Waiting for incoming connections..."); c = sizeof(struct sockaddr_in);
while(new_socket=accept(socket_desc,(struct sockaddr *)&client, (socklen_t*)&c)) { puts("Connection accepted");
//Reply to the client message = "Hello Client , I have received your connection.\n"; write(new_socket , message , strlen(message));
pthread_t sniffer_thread; new_sock = malloc(1); *new_sock = new_socket;
if(pthread_create(&sniffer_thread,NULL,connect_server,(void*)new_sock) > 0) { printf("could not create thread"); return 1; } puts("handler assignment"); if(new_socket < 0) { printf("accept failed"); return 1; } } return 0; }
void *connect_server(void *socket_desc) { int sock = *(int *)socket_desc; int read_size; char *message,client_message[2000]; message = "Greetings!I am your connection handler\n"; write(sock,message,strlen(message));
message = "It is my duty to communicate with you\n"; write(sock,message,strlen(message)); while( (read_size = recv(sock,client_message,2000,0) ) > 0 ) { if( strcmp(client_message,"exit") == 0) { fflush(stdout); break; } write(sock,client_message,strlen(client_message)); }
if(read_size == 0) { puts("client disconnect"); fflush(stdout); } else if(read_size == -1) { puts("recv failed"); }
return 0; }
|