#include "sys/types.h"
#include
#include
#include
#include
void main(){
int sfd,clisize,cfd,port;
struct sockaddr_in server,client;
char msg1[50]="",msg2[50]="";
sfd = socket(AF_INET,SOCK_STREAM,0);
if(sfd==-1){
printf("\nCannot Create Socket");
}
printf("\nEnter the port address:");
scanf("%d",&port);
server.sin_family = AF_INET;
server.sin_port = port;
server.sin_addr.s_addr = inet_addr("127.0.0.1");
if(bind(sfd,(struct sockaddr *)&server,sizeof(server))!=0){
printf("\nCannot Bind");
}
if(listen(sfd,0)!=0){
printf("\nError In Listening");
}
printf("\nServer Ready and Waiting for Client.............\n");
clisize = sizeof(client);
cfd = accept(sfd,(struct sockaddr *)&client,&clisize);
if(cfd==-1){
printf("\nCannot Accept client Socket");
}
for(;;){
recv(cfd,msg1,sizeof(msg1),0);
printf("\nClient:%s",msg1);
printf("\nServer :");
scanf("%s",msg2);
send(cfd,msg2,sizeof(msg2),0);
if(strcmp(msg2,"end")==0)
break;
}
close(sfd);
close(cfd);
}
TCPClient.c
#include
#include
#include
#include
#include
void main(){
struct sockaddr_in server,client;
int sfd,port;
char msg1[50]="",msg2[50]="";
sfd = socket(AF_INET,SOCK_STREAM,0);
if(sfd ==-1){
printf("\nCannot Create socket");
}
printf("\nEnter the port address:");
scanf("%d",&port);
server.sin_family = AF_INET;
server.sin_port = port;
server.sin_addr.s_addr = inet_addr("127.0.0.1");
printf("\nClient Ready");
if(connect(sfd,(struct sockaddr *)&server,sizeof(server))!=0){
printf("\nCannot Connect");
}
for(;;){
printf("\nClient:");
scanf("%s",msg1);
send(sfd,msg1,sizeof(msg1),0);
recv(sfd,msg2,sizeof(msg2),0);
printf("\nServer:%s",msg2);
if(strcmp(msg2,"end")==0)
break;
}
close(sfd);
}
OUPUT
sarju@krishnakripa:~$ gcc TCPServer.c -o server
sarju@krishnakripa:~$ ./server
Enter the port address:2002
Server Ready and Waiting for Client.............
Client:hi
Server :hi
Client:end
Server :end
sarju@krishnakripa:~$
sarju@krishnakripa:~$ gcc TCPClient.c -o client
sarju@krishnakripa:~$ ./client
Enter the port address:2002
Client Ready
Client:hi
Server:hi
Client:end
Server:endsarju@krishnakripa:~$
0 comments:
Post a Comment