CHAT APPLICATION USING UDP
By karthick
, in
IMPLEMENTATION OF CHAT APPLICATION USING UDP
,
0 Comments
Server program
#include<stdio.h>
#include<sys/socket.h>
#include<netdb.h>
#include<string.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<stdlib.h>
int
main()
{
int
listenfd,connfd,n,len,port;
char
buff[1024], str[1024];
struct
sockaddr_in servaddr;
listenfd=socket(AF_INET,SOCK_DGRAM,0);
if
(listenfd<0)
printf("Unable
to create a socket");
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=htonl
(INADDR_ANY);
printf("Enter
the port number");
scanf("%d",&port);
servaddr.sin_port=htons
(port);
bind
(listenfd,(struct sockaddr*)&servaddr,sizeof(servaddr));
len=sizeof(servaddr);
while(strcmp(buff,"bye")!=0)
{
recvfrom(listenfd,buff,1024,0,(struct
sockaddr*)&servaddr,&len);
printf("From
client :%s\n",buff);
printf("Server:");
scanf("%s",str);
write(listenfd,str,strlen(str));
sendto(listenfd,str,sizeof(str),0,(struct
sockaddr*)&servaddr,len);
}
return
0;
}
Client program
#include<stdio.h>
#include<sys/socket.h>
#include<netdb.h>
#include<string.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<stdlib.h>
int
main(int argc,char **argv)
{
int
sockfd,n,len,port;
char
buff[1024],str[1024];
struct
sockaddr_in servaddr;
sockfd
= socket(AF_INET,SOCK_DGRAM,0);
if
(sockfd<0)
printf("Unable
to create a socket");
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=htonl
(INADDR_ANY);
//servaddr.sin_addr.s_addr=inet_addr(argv[1];
printf("Enter
the port number");
scanf("%d",&port);
servaddr.sin_port=htons(port);
connect(sockfd,(struct
sockaddr*)&servaddr,sizeof(servaddr));
while(strcmp(buff,"bye")!=0)
{
printf("client:");
//gets(str);
scanf("%s",str);
sendto(sockfd,str,sizeof(str),0,(struct
sockaddr*)&servaddr,len);
write(sockfd,str,strlen(str));
printf("From
Server:");
recvfrom(sockfd,buff,1024,0,(struct
sockaddr*)&servaddr,&len);
fputs(buff,stdout);
printf("\n");
}
close(sockfd);
return
0;
}
OUTPUT
SERVER
[11ca013@mcalinux
network]$ cc 4udpser.c
[11ca013@mcalinux
network]$ ./a.out
Enter
the port number4587
From
client :hi
Server :how_are_you
From
client :i_am_fine
Server :ok_where_are_you
From
client :i_am_fine
Server :ok
From
client :bye
CLIENT
[11ca013@mcalinux
network]$ cc 4udpcli.c
[11ca013@mcalinux
network]$ ./a.out
Enter
the port number4587
Client :hi
From
Server :how_are_you
Client :i_am_fine
From
Server :ok
Client :bye
0 Response to "CHAT APPLICATION USING UDP"
Post a Comment