Connectionless Program
UDP Client Server Communication ( Connectionless Data Transfer )
Sender side Function:
socket();
bind();
recvfrom(); / sendto();
close();
Client side Functions:
socket();
sendto() / recvfrom();
close();
// UDP SERVER PROGRAM
#include <stdio.h>
#include <errno.h>
#include <sys/socket.h>
#include <resolv.h>
#include<netinet/in.h>
#include<sys/types.h>
int main()
{
char buff[2000];
int sd,connfd,len;
struct sockaddr_in servaddr,cliaddr;
sd = socket(AF_INET, SOCK_DGRAM, 0);
if(sd==-1)
{
printf(" socket not created in server\n");
exit(0);
}
else
{
printf("socket created in server\n");
}
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = INADDR_ANY;
servaddr.sin_port = htons(7802);
if ( bind(sd, (struct sockaddr *)&servaddr, sizeof(servaddr)) != 0 )
printf("Not binded\n");
else
printf("Binded\n");
len=sizeof(cliaddr);
recvfrom(sd,buff,1024,0,
(struct sockaddr *)&cliaddr, &len);
printf("UDP Server received msg from UDP client %s",buff);
close(sd);
return(0);
}
// UDP CLIENT PROGRAM
#include <stdio.h>
#include <errno.h>
#include <sys/socket.h>
#include <resolv.h>
#include<netinet/in.h>
#include<sys/types.h>
int main()
{
char buff[2000];
int sockfd,connfd,len;
struct sockaddr_in servaddr,cliaddr;
// create socket in client side
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if(sockfd==-1)
{
printf(" socket not created in client\n");
exit(0);
}
else
{
printf("socket created in client\n");
}
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = INADDR_ANY; // ANY address or use specific address
servaddr.sin_port = htons(7802); // Port address
printf("Type ur UDP client message\n");
scanf("%s",buff);
// send msg to server
sendto(sockfd, buff, strlen(buff), 0,
(struct sockaddr *)&servaddr, sizeof(struct sockaddr));
//close client side connection
close(sockfd);
return(0);
}
Steps:
1) Compile and Run Server Program cc udpserver.c ./a.out
2) Compile and Run Client Program cc udpclient.c ./a.out
3) Enter Message in Client