udp client sever chat program
UDP server
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<string.h>
#include<sys/socket.h>
main()
{
int sd,i=0,port=5015;
char
buffer[30];
unsigned
int t;
struct
sockaddr_in ser,cli;
if((sd=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP))==-1)
{
printf("Error in Socket creation with server\n");
return
0;
}
bzero((char *)&ser,sizeof(ser));
printf("The port address is %d\n",port);
ser.sin_family=AF_INET;
ser.sin_port=htons(port);
ser.sin_addr.s_addr=inet_addr("192.168.0.200");
if(bind(sd,(struct sockaddr *)&ser,sizeof(ser))==-1)
{ printf("Error in Binding problem due to port busy");
return
(0);
}
printf("\t\tServer\n");
t=sizeof(cli);
printf("\n
client accepted\n");
while(1)
{
recvfrom(sd,buffer,50,0,(struct sockaddr*)&cli,&t);
printf(" Data from client:");
puts(buffer);
printf(" Data to client:");
gets(buffer);
sendto(sd,buffer,50,0,(struct sockaddr*)&cli,sizeof(cli));
if(buffer[i]=='*')
break;
}
close(sd);
return 0;
}
Server o/p:
[cs2910007@localhost
netlab]$ ./a.out
The port address is 5015
Server
client accepted
Data from client:58
Data to client:856
Data from client:412
Data to client:952
Data from client:782
Data to client:*
[cs2910007@localhost
netlab]$
UDP Client CHAT
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<string.h>
#include<sys/socket.h>
main()
{
int
sd,i=0,port=5015;
unsigned
int t;
char
cont[30]="\0";
struct
sockaddr_in ser,cli;
if((sd=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP))==-1)
{
printf("Error in Socket creation with the server\n");
return 0;
}
bzero((char
*)&ser,sizeof(ser));
printf("The port address is %d\n",port);
ser.sin_family=AF_INET;
ser.sin_port=htons(port);
ser.sin_addr.s_addr=inet_addr("192.168.0.200");
if(connect(sd,(struct sockaddr *)&ser,sizeof(ser))==-1)
{
printf("Error in connecting due to port busy");
return 0;
}
t=sizeof(ser);
printf("This is client\n");
while(1)
{
printf(" Data to server:");
gets(cont);
sendto(sd,cont,50,0,(struct sockaddr*)&ser,sizeof(ser));
recvfrom(sd,cont,50,0,(struct sockaddr*)&ser,&t);
printf(" Data from server:");
puts(cont);
if(cont[i]=='*')
break;
}
close(sd);
return 0;
}
Client o/p:
The port address is 5015
This is client
Data to server:58
Data from server:856
Data to server:412
Data from server:952
Data to server:782
Data from server:*
[cs2910007@localhost
netlab]$
No comments:
Post a Comment