You are on page 1of 4

Ex 02 Applications using TCP sockets l: Echo

client and echo server


ECHO SERVER:

#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
int sid,bd,lis,acptd,rd,sd;
struct sockaddr_in sin;
char buf[10];
socklen_t len;
sid=socket(PF_INET,SOCK_STREAM,0);
if(sid == -1)
{
printf("\n Error in creating socket \n");
exit(-1);
}
printf("\n The socket is created successfully");
memset(&sin,0,sizeof(sin));
sin.sin_family=AF_INET;
sin.sin_port=htons(5110);
sin.sin_addr.s_addr=htonl(INADDR_ANY);
bd=bind(sid,(struct sockaddr*)&sin,sizeof(sin));
if(bd < 0)
{
printf("\n Binding failed \n");
exit(-1);
}
printf("\n Binding Completed");
lis=listen(sid,5);
if(lis < 0)
{
printf("\n Error in listening \n");
exit(-1);
}
printf("\n Listening is completed");
len=sizeof(sin);
acptd=accept(sid,(struct sockaddr*)&sin,&len);
if(accept < 0)
{
printf("\n Error in Accepting \n");
exit(-1);
}
printf("\n Client is Accepted \n");
do
{
rd=read(acptd,buf,10);
if(rd < 0)
{
printf("\n Error in receiving the date from the client \n");
exit(-1);
}
printf(" Message received from client: %s \n",buf);
sd=send(acptd,buf,10,0);
if(sd < 0)
{
printf("\n Error in sending the data to the client \n");
exit(-1);
}
}while(strcasecmp(buf,"END")!=0);
shutdown(sid,2);
close(sid);
}

ECHO CLIENT:

#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
int sid,con,sd,rd;
struct sockaddr_in sin;
char buf[10];
sid=socket(PF_INET,SOCK_STREAM,0);
if(sid == -1)
{
printf("\n Error in creating the socket \n");
exit(-1);
}
printf("\n Socket created successfully");
memset(&sin,0,sizeof(sin));
sin.sin_family=AF_INET;
sin.sin_port=htons(5110);
sin.sin_addr.s_addr=htonl(INADDR_ANY);
con=connect(sid,(struct sockaddr*)&sin,sizeof(sin));
if(con < 0)
{
printf("\n The connection established falied \n");
exit(-1);
}
printf("\n Connection established successfully \n");
do
{
printf(" Enter the string: ");
scanf("%s",buf);
sd=send(sid,buf,10,0);
if(sd < 0)
{
printf("\n Error in sending the data to the server \n");
exit(-1);
}
rd=read(sid,buf,10);
if(rd < 0)
{
printf("\n Error in reading the data send by the server \n");
exit(-1);
}
printf(" The content received from sender is: %s \n",buf);
}while(strcasecmp(buf,"END")!=0);
shutdown(sid,2);
close(sid);
}

You might also like