Chat Program Using UDP Socket perform operation in Server CS1305- NETWORK LAB

Step by Step algorithm UDP char program
Start the Chat program
Create a socket using socket()
Bind it with a local protocol
Receive the message from client using recvfrom() until the message “bye”;
Response t the client by sendto().
Stop the program
See the BASIC syntax for UDP CHAT program

Source code UDP Server chat program CS1305- NETWORK LAB
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<string.h>
int main(int argc,char **argv)
{
struct sockaddr_in mysock,newsock;
int sockfd;
char msg[1024];
int size,val;
if((sockfd=socket(AF_INET,SOCK_DGRAM,0))<0)
{
perror("no socket");
exit(0);
}
size=sizeof(struct sockaddr);
socklen_t len=sizeof(newsock);
bzero(&mysock,size);
mysock.sin_family=AF_INET;
mysock.sin_port=htons(3000);
mysock.sin_addr.s_addr=htonl(INADDR_ANY);
if((bind(sockfd,(struct sockaddr*)&mysock,size))<0)
{
perror("no bind");
exit(0);
}
if(strcmp(msg,"bye")==0)
exit(0);
while(strcmp(msg,"bye")!=0)
{
if((val=recvfrom(sockfd,msg,1024,0,(struct sockaddr*)&newsock,&len))<0)
{
perror(" ");
exit(0);
}
printf("\n from client");
printf("%s",msg);
if(strcmp(msg,"bye")==0)
{
printf("\nserver");
scanf("%s",msg);
exit(0);
}
printf("\n server");
scanf("%s",msg);
if((sendto(sockfd,msg,val,0,(struct sockaddr*)&newsock,len))<0)
{
perror("\n no send");
exit(0);
}
}
close(sockfd);
return 0;
}

Output UDP Server CS1305- NETWORK LAB
[it28@localhost lapprogramsystem]$cc chat1.c
[it28@localhost lapprogramsystem]$./a.out
From client: lapprogramsystem
Server: server system
From Client: john
Server: Alex
From client:jebrose

Related post