B. TCP Socket Programming in Unix Using C Programming

ECHO CLIENT USING TCP

SERVER:

#include<netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include<stdio.h>
#include <arpa/inet.h>
#include <string.h>
#include<fcntl.h>
main()
{
int sd,cd;
char buf[100]="";
struct sockaddr_in ser;
sd=socket(AF_INET,SOCK_STREAM,0);
if(sd<0)
printf("SOCKET NOT CREATED\n");
bzero(&ser,sizeof(struct sockaddr_in));
ser.sin_family=AF_INET;
ser.sin_port=htons(1012);
inet_aton("172.16.29.78",&ser.sin_addr);
int b=bind(sd,(struct sockaddr *)&ser,sizeof(ser));
printf("BIND VALUE:%d\n",b);
listen(sd,5);
for(;;)
{
cd=accept(sd,NULL,NULL);
int pid=fork();
if(pid==0)
{
printf("accept value %d\n",cd);
read(cd,buf,100);
printf("MESSAGE FROM CLIENT:%s\n",buf);
write(cd,buf,strlen(buf));
close(cd);
}
}
close(sd);
}

CLIENT:

#include<netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include<stdio.h>
#include <arpa/inet.h>
#include <string.h>
#include<fcntl.h>
main()
{
int sd,cd;
char buf[100]="",buf1[100]="";
struct sockaddr_in ser;
sd=socket(AF_INET,SOCK_STREAM,0);
if(sd<0)
printf("SOCKET NOT CREATED\n");
bzero(&ser,sizeof(struct sockaddr_in));
ser.sin_family=AF_INET;
ser.sin_port=htons(1012);
inet_aton("172.16.29.78",&ser.sin_addr);
int c=connect(sd,(struct sockaddr *)&ser,sizeof(ser));
printf("CONNET %d\n",c);
if(c<0)
printf("CONNECTION FAILED\n");
for(;;)
{
printf("ENTER THE MESSAGE");
scanf("%s",buf);
write(sd,buf,strlen(buf));
read(sd,buf1,100);
printf("RECEIVED FROM SERVER%s\n",buf1);
}
close(sd);
close(cd);
}


OUTPUT:

SERVER:

cc tserver.c -o tser
./tser
BIND VALUE:0
accept value 4
MESSAGE FROM CLIENT:Hello

CLIENT:


cc tclient.c -o tcli
./tcli
CONNET 0
ENTER THE MESSAGE
Hello