tcp_server.c
#include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<string.h> #include<sys/socket.h> #include<sys/types.h> #include<arpa/inet.h> int main() { int sid,new_sid; char buffer[100]; pid_t child; struct sockaddr_in s,new_s; int size_of_new_s=sizeof(new_s); sid=socket(AF_INET,SOCK_STREAM,0); if(sid<0) { printf("[+]Error in socket creation :\n"); exit(1); } printf("socket created:\n"); s.sin_family=AF_INET; s.sin_port=htons(6666); s.sin_addr.s_addr=inet_addr("127.0.0.1"); if(bind(sid,(struct sockaddr *)&s,sizeof(s))<0) { printf("[+]Error in binding: \n "); exit(1); } printf("Binding with port is Completed: \n"); if(listen(sid,10)==0) { printf("listening.............\n"); } else printf("[+]error in listening: \n"); while(1) { new_sid=accept(sid,(struct sockaddr*)&new_s,&size_of_new_s); if(new_sid<0) { //printf("Error in connection acception :\n"); exit(1); } printf("connection is established with %s:%d \n",inet_ntoa(new_s.sin_addr),ntohs(new_s.sin_port)); if((child=fork())==0) { close(sid); while(1) { recv(new_sid,buffer,100,0); if(strcmp(buffer,"exit")==0) { printf("Disconnected from %s:%d \n",inet_ntoa(new_s.sin_addr),ntohs(new_s.sin_port)); break; } else { printf("\n Client of port No://%d// : %s \n",ntohs(new_s.sin_port),buffer); //printf("\n massge to Client of port No://%d// :",ntohs(new_s.sin_port)); //scanf("%s",buffer); send(new_sid,buffer,100,0); bzero(buffer,sizeof(buffer)); } } } } close(new_sid); }
tcp_client.c
#include<stdio.h> #include<sys/types.h> #include<stdlib.h> #include<sys/socket.h> #include<arpa/inet.h> #include<unistd.h> #include<string.h> int main() { int sid; struct sockaddr_in s; //nsz=sizeof(ns); char buffer[100]; sid=socket(AF_INET,SOCK_STREAM,0); pid_t pid; if(sid<0) { printf("[-]Error in socket Creation:\n"); exit(0); } printf("[+]SOcket created:\n"); s.sin_family=AF_INET; s.sin_port=htons(6666); s.sin_addr.s_addr=inet_addr("127.0.0.1"); if(connect(sid,(struct sockaddr*)&s,sizeof(s))<0) { printf("[-]Error in Connection:\n"); exit(1); } printf("[+]Connection completed:\n"); while(1) { printf("\nClient:"); scanf("%s",buffer); send(sid,buffer,100,0); if(strcmp(buffer,"exit")==0) { //printf("Disconnected from:%s : %d",inet_ntoa(ns.sin_addr),ntohs(ns.sin_port)); close(sid); break; } //printf("\nClient port: %d::%s",ntohs(ns.sid_port),buffer); bzero(buffer,sizeof(buffer)); } }
Post a Comment