UDP Client Server using connect | C implementation
UDP is a connection less protocol. There is no connection is established between client and server. Creating Standard UDP Client/Server is discussed here
Prerequisite : Socket Programming in C/CPP | UDP server-client implementation
In UDP, the client does not form a connection with the server like in TCP and instead, It just sends a datagram. Similarly, the server need not to accept a connection and just waits for datagrams to arrive. We can call a function called connect() in UDP but it does not result anything like it does in TCP. There is no 3 way handshake. It just checks for any immediate errors and store the peer’s IP address and port number. connect() is storing peers address so no need to pass server address and server address length arguments in sendto().
Necessary Functions :
int connect(int sockfd, const struct sockaddr *servaddr,
socklen_t addrlen);
returns : 0 if OK -1 on error
arguments :
sockfd : File descriptor of socket to be connected.
struct sockaddr *servaddr : server address structure.
addrlen : length of server address structure.
Below is the implementation showing message transfer between server-client :
UDP Server code :
#include <stdio.h>
#include <strings.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include<netinet/in.h>
#define PORT 5000
#define MAXLINE 1000
int main()
{
char buffer[100];
char *message = "Hello Client" ;
int listenfd, len;
struct sockaddr_in servaddr, cliaddr;
bzero(&servaddr, sizeof (servaddr));
listenfd = socket(AF_INET, SOCK_DGRAM, 0);
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);
servaddr.sin_family = AF_INET;
bind(listenfd, ( struct sockaddr*)&servaddr, sizeof (servaddr));
len = sizeof (cliaddr);
int n = recvfrom(listenfd, buffer, sizeof (buffer),
0, ( struct sockaddr*)&cliaddr,&len);
buffer[n] = '\0' ;
puts (buffer);
sendto(listenfd, message, MAXLINE, 0,
( struct sockaddr*)&cliaddr, sizeof (cliaddr));
}
|
UDP Client code :
#include <stdio.h>
#include <strings.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include<netinet/in.h>
#include<unistd.h>
#include<stdlib.h>
#define PORT 5000
#define MAXLINE 1000
int main()
{
char buffer[100];
char *message = "Hello Server" ;
int sockfd, n;
struct sockaddr_in servaddr;
bzero(&servaddr, sizeof (servaddr));
servaddr.sin_addr.s_addr = inet_addr( "127.0.0.1" );
servaddr.sin_port = htons(PORT);
servaddr.sin_family = AF_INET;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (connect(sockfd, ( struct sockaddr *)&servaddr, sizeof (servaddr)) < 0)
{
printf ( "\n Error : Connect Failed \n" );
exit (0);
}
sendto(sockfd, message, MAXLINE, 0, ( struct sockaddr*)NULL, sizeof (servaddr));
recvfrom(sockfd, buffer, sizeof (buffer), 0, ( struct sockaddr*)NULL, NULL);
puts (buffer);
close(sockfd);
}
|
Outputs:
Last Updated :
17 Apr, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...