/* Using UDP client/server echo programming first the client will send a message to server*/
/*The server reads the message sent by client and store in character array*/
/* The server will send the same message stored in character array to client*/
/* The client will display the same message again on screen*/
/*udp Server.c*/
#include<unistd.h>
#include<sys/socket.h>
#include<stdio.h>
#include<string.h>
#include<netinet/in.h>
#include<sys/types.h>
#include<errno.h>
#define MAXLINE 5555
void main(int argc,char *argv[])
{
int sockfd,n;
unsigned short port;
socklen_t len;
char mesg[1024];
struct sockaddr_in servaddr,cliaddr;
port=(unsigned short)atoi(argv[1]);
if((sockfd=socket(AF_INET,SOCK_DGRAM,0))<0)
printf("error in socket creation");
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
servaddr.sin_port=htons(port);
len=sizeof(servaddr);
if(bind(sockfd,(struct sockaddr *)&servaddr,len)<0)
perror("\nbind");
for(;;)
{
len=sizeof(cliaddr);
n=recvfrom(sockfd,&mesg,MAXLINE,0,(struct sockaddr *)&cliaddr,&len);
sendto(sockfd,&mesg,n,0,(struct sockaddr *)&cliaddr,len);
}
}
output:
/home/anil/~ cc udpserver.c
/home/anil/~ ./a.out 4455
-
/*open another new terminal for udp client program*/
/*udpclient.c*/
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<string.h>
#include<netinet/in.h>
#include<errno.h>
#define MAXLINE 5566
void main(int argc,char **argv[])
{
int sockfd,n,len;
char mesg[1024];
unsigned short port;
char sendline[MAXLINE],recvline[MAXLINE];
struct sockaddr_in servaddr;
if((sockfd=socket(AF_INET,SOCK_DGRAM,0))<0)
{
perror("socket");
}
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
port=(unsigned short)atoi(argv[1]);
servaddr.sin_port=htons(port);
if((inet_pton(AF_INET,argv[2],&servaddr.sin_addr))<0)
{
perror("inet_pton");
}
len=sizeof(servaddr);
while(fgets(sendline,MAXLINE,stdin)!=NULL)
{
sendto(sockfd,&sendline,strlen(sendline),0,(struct sockaddr *)&servaddr,len);
n=recvfrom(sockfd,&recvline,MAXLINE,0,(struct sockaddr *)&servaddr,&len);
recvline[n]=0;
printf("\n %s",recvline);
}
}
output:
/home/anil/~ cc udpclient.c
/home/anil/~ ./a.out 4455 127.0.0.1
hi
hi
hello
hello
socket programming,example of client server programming using tcp, example of client server programming using udp, udp echo program. tcp echo program, ping program, one to one chat application, concurrent server, iterative server.bind listen accept socket read from write from, send recieve
No comments:
Post a Comment