Professional Documents
Culture Documents
EX. NO:
ALGORITHM
SERVER
Step 1: Start the program
Step 2: Create an unnamed socket for server using parameters AF_INET as domain
and SOCK_STREAM
Step 3: Name the socket using bind() system call
Step 4: Create the connection queue and wait for listen() system call
Step 5: Accept the connection using accept() system call when client request for
connection
Step 6: Get the message which has to be send to the client and catch that was not equal
to bye
CLIENT:
Step 1: Start the program
Step 2: Create an unnamed socket for client using socket system
Step 3: Call with parameters AF_INET as domain
Step 4: Read the message from the server socket and compare with bye
Step 5: If message is not equal to bye then print the message to the server
Step 6: If message is equal to bye then print good bye and terminate the process
Step 11: Stop the process
PROGRAM
#include<stdio.h>
#include<string.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<stdlib.h>
#include<sys/types.h>
main()
{
int sfd , cfd , lfd,l,p;
char recvmsg[20],sendmsg[20];
struct sockaddr_in servaddr,cliaddr;
printf("enter the port no:");
scanf("%d",&p);
sfd=socket(AF_INET,SOCK_STREAM,0);
if(sfd<0)
{
printf("socket is not created...");
exit(0);
}
else
printf("socket is created...");
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(p);
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
{
recv(lfd,recvmsg,20,0);
printf("%s",recvmsg);
send(lfd,recvmsg,20,0);
}while(strncmp("bye",recvmsg,3)!=0);
}
CLIENT
#include<stdio.h>
#include<string.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<stdlib.h>
#include<netinet/in.h>
main()
{
int sfd,cfd,p,len;
char sendmsg[20],recvmsg[20];
struct sockaddr_in servaddr;
printf("enter the port no:");
scanf("%d",&p);
sfd=socket(AF_INET,SOCK_STREAM,0);
if(sfd<0)
{
printf("socket is not created sucessfully...");
exit(0);
}
else
printf("socket is created sucessfully..");
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(p);
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
cfd=connect(sfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
if(cfd<0)
{
printf("connection is not established...");
exit(0);
}
else
printf("connection is established...");
do
{
fgets(sendmsg,20,stdin);
len=strlen(sendmsg);
sendmsg[len-1]!='\0';
send(sfd,sendmsg,20,0);
recv(sfd,recvmsg,20,0);
printf("%s",recvmsg);
}
while(strncmp("bye",recvmsg,3)!=0);
OUTPUT:
SERVER:
Enter the port: 2119
2119
Socket is created
Binded
Accepted
Received messages
Hello how are you?
Bye
CLIENT:
Enter the port: 2119
2119
Socket is created
Connected
Hello how are you?
Bye
RESULT
Thus the client server chat program using tcp echo was executed and the output was
verified successfully.