How to do it…

  1. Define two variables of type sockaddr_in. Invoke the bzero function to initialize the structure.
  2. Invoke the socket function to create a socket. The address family that's supplied for the socket is AF_INET, and the socket type that's selected is datagram type.
  1. Initialize the members of the sockaddr_in structure to configure the socket. The port number that's specified for the socket is 2000. Use INADDR_ANY, a special IP address, to assign an IP address to the socket.
  2. Call the bind function to assign the address to it.
  3. Call the recvfrom function to receive the message from the UDP socket, that is, from the client machine. A null character, \0, is added to the message that's read from the client machine and is displayed on the screen. Enter the reply that is to be sent to the client.
  4. Invoke the sendto function to send the reply to the client.

The server program, udps.c, for waiting for a message from the client and sending a reply to it using a UDP socket is as follows:

#include <stdio.h>
#include <strings.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include<netinet/in.h>
#include <stdlib.h>

int main()
{
char msgReceived[255];
char msgforclient[255];
int UDPSocket, len;
struct sockaddr_in server_Address, client_Address;
bzero(&server_Address, sizeof(server_Address));
printf("Waiting for the message from the client\n");
if ( (UDPSocket = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {
perror("Socket could not be created");
exit(1);
}
server_Address.sin_addr.s_addr = htonl(INADDR_ANY);
server_Address.sin_port = htons(2000);
server_Address.sin_family = AF_INET;
if ( bind(UDPSocket, (const struct sockaddr *)&server_Address,
sizeof(server_Address)) < 0 )
{
perror("Binding could not be done");
exit(1);
}
len = sizeof(client_Address);
int n = recvfrom(UDPSocket, msgReceived, sizeof(msgReceived), 0,
(struct sockaddr*)&client_Address,&len);
msgReceived[n] = '\0';
printf("Message received from the client: ");
puts(msgReceived);
printf("Enter the reply to be sent to the client: ");
gets(msgforclient);
sendto(UDPSocket, msgforclient, 255, 0, (struct
sockaddr*)&client_Address, sizeof(client_Address));
printf("Reply to the client sent \n");
}

Let's go behind the scenes.