Basic example udp server and client

  • In this program, you are going to learn

  • How to create a Socket ?

  • How to bind a socket ?

  • How to send a data ?

  • How to recv a data ?

Let us answer few basic questions in this socket

What does socket(AF_INET SOCK_DGRAM,IPPROTO_UDP) create?

What does AF_INET signify in socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)?

Why might you choose SOCK_DGRAM when creating a socket?

What is the purpose of IPPROTO_UDP in socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)?

How does a UDP socket differ from a TCP socket created using socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)?

What is the typical use case for a UDP socket created with socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)?

How would you bind a specific IP address and port to a UDP socket created using socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)?

https://www.plantuml.com/plantuml/svg/PP0_3u8m4CNtVegwc68wEEi22XXY50Awk3IbFI8HA6aBWvzUgWx-cIxlthttIyutbcixj0sQsIkqW4tF1JIyH4y3hOmIDx0aY5boZ4uK5-bspy9T7XmeJh8iJqyfEuUPjqQhikuaCQ17qEmLevWOgmTXiTDSIhtmvkyBfoWszHrKHJvsdglI8CPAg_QthXog2gROvXp7KSwAv19HlFp7u8aZcXew--RCtM2Evkh9g6hfYKOP-2PCfh6gHpvqSdhA0m==
  • There are many functions used in socket. We can classify those functions based on functionalities.

    • Create Socket

    • Bind Socket

    • Recvfrom data_packet

    • Close socket

  • socket() is used to create a new socket. For example,

server_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  • bind() is used to associate the socket with a specific address and port. For example,

ret = bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr));
  • recvfrom is commonly used with UDP sockets, where communication is connectionless. it provides information about the source (sender) of the data, including the sender’s IP address and port number. For example,

len = recvfrom(server_socket, buffer, BUFFER_SIZE, 0, (struct sockaddr*)&client_addr, &addr_size);
  • close is used to close the socket To free up system resources associated with the socket. For example,

(void)close(server_socket);
  • See the full program below,

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define BUFFER_SIZE 1024

void validate_convert_port(
char *port_str,
struct sockaddr_in *sock_addr)
{
  int port;

  if (port_str == NULL) {
     perror("Invalid port_str\n");
     exit(EXIT_FAILURE);
 }

 if (sock_addr == NULL) {
     perror("Invalid sock_addr\n");
     exit(EXIT_FAILURE);
 }

 port = atoi(port_str);

 if (port == 0) {
   perror("Invalid port\n");
   exit(EXIT_FAILURE);
 }

 sock_addr->sin_port = htons(
 (uint16_t)port);
 printf("Port: %d\n",
 ntohs(sock_addr->sin_port));
}

int main(int argc, char *argv[]) 
{
  int server_socket;
  int ret;
  struct sockaddr_in 
  server_addr, 
  client_addr;
  socklen_t addr_size = sizeof(
  client_addr);
  char buffer[BUFFER_SIZE];

  if (argc != 2) {
    printf("%s <port-number>",
    argv[0]);
    return -1;
  }

  server_socket = socket(AF_INET,
                  SOCK_DGRAM,
                  IPPROTO_UDP);

  if (server_socket < 0) {
    perror("Socketfailed");
    return -2;
  }

  server_addr.sin_family = AF_INET;
  server_addr.sin_addr.s_addr = 
  INADDR_ANY;
  validate_convert_port(argv[1], 
  &server_addr);

  ret = bind(server_socket,
  (struct sockaddr *)&server_addr,
  sizeof(server_addr));

  if (ret < 0) {
    perror("Bind failed");
    (void)close(server_socket);
    return -3;
  }

  ret = recvfrom(server_socket, 
  buffer, 
  BUFFER_SIZE, 0, 
  (struct sockaddr *)&client_addr, 
  &addr_size);

  if (ret < 0) {
    perror("recvfrom");
    (void)close(server_socket);
    return -4;
  }

  printf("received: %s\n", buffer);

  (void)close(server_socket);

  return 0;
}

1$ gcc -o server server.c
2
3$ sudo ./server 8080
4
5Port: 8080
6received: Hello from client!
https://www.plantuml.com/plantuml/svg/LKyz3u8m5Dpv5S_5jAQ3iouGKKECGX3d1ieZ4WibxOF1Ns-HHSVxojs5ZafBOwU35JsnGt13gL2NLV0LWfqpweN4efDCRiT2m3qzN6HypgEhW2JByhH8vIFE-DvRiQ_9CALRx4akGG7Ls3He1JYo6dksG2vWAu1vRbG4ixMiQxlXQuTsGYjd901S-qRJi1-IpqLiCctDbJOE_zkywCWCGUYN-4yV
  • There are many functions used in socket. We can classify those functions based on functionalities.

    • Create Socket

    • Sendto data_packet

    • Close socket

  • socket is used to create a new socket. For example,

client_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  • sendto is used to send the encoded message to the specified server address and port using a UDP socket. For example,

ret = sendto(client_socket, buffer, strlen(buffer), 0, (struct sockaddr*)&server_addr, sizeof(server_addr));
  • close is used to close the socket To free up system resources associated with the socket. For example,

(void)close(client_socket);
  • See the full program below,

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define BUFFER_SIZE 1024

void validate_convert_port(
char *port_str,
struct sockaddr_in *sock_addr)
{
  int port;

  if (port_str == NULL) {
     perror("Invalid port_str\n");
     exit(EXIT_FAILURE);
 }

 if (sock_addr == NULL) {
     perror("Invalid sock_addr\n");
     exit(EXIT_FAILURE);
 }

 port = atoi(port_str);

 if (port == 0) {
   perror("Invalid port\n");
   exit(EXIT_FAILURE);
 }

 sock_addr->sin_port = htons(
 (uint16_t)port);
 printf("Port: %d\n",
 ntohs(sock_addr->sin_port));
}

void validate_convert_addr(
char *ip_str,
struct sockaddr_in *sock_addr)
{
  if (ip_str == NULL) {
     perror("Invalid ip_str\n");
     exit(EXIT_FAILURE);
 }

 if (sock_addr == NULL) {
     perror("Invalid sock_addr\n");
     exit(EXIT_FAILURE);
 }
 
 printf("IP Address: %s\n", ip_str);

 if (inet_pton(AF_INET, ip_str,
 &(sock_addr->sin_addr)) <= 0) {
    perror("Invalid address\n");
    exit(EXIT_FAILURE);
  }
}

int main(int argc, char *argv[]) 
{
  int client_socket;
  int ret;
  struct sockaddr_in 
  server_addr;
  char buffer[BUFFER_SIZE] = "Hello from client!";

  if (argc != 3) {
    printf("%s<port-number><ip-addr>\n",
    argv[0]);
    return -1;
  }

  client_socket = socket(AF_INET,
                  SOCK_DGRAM,
                  IPPROTO_UDP);

  if (client_socket < 0) {
    perror("Socket failed");
    return -2;
  }

  server_addr.sin_family = AF_INET;
  validate_convert_port(argv[1], 
  &server_addr);
  validate_convert_addr(argv[2], 
  &server_addr);

  ret = sendto(client_socket, 
  buffer, 
  strlen(buffer), 0, 
  (struct sockaddr *)&server_addr, 
  sizeof(server_addr));

  if (ret < 0) {
    perror("sendto");
    (void)close(client_socket);
    return -3;
  }

  printf("Messagesent: %s\n", 
  buffer);

  (void)close(client_socket);

  return 0;
}

1$ gcc -o client client.c
2
3$ sudo ./client 8080 127.0.0.1
4
5Port: 8080
6IP Address: 127.0.0.1
7Messagesent: Hello from client!

$ sudo ./server 8080 127.0.0.1

$ sudo ./client 8080 127.0.0.1

program to run with elevated privileges, listen on port 8080, and bind to the loopback address 127.0.0.1.

<port_number> <ip_address> decided by the user based on the connection.

https://www.plantuml.com/plantuml/svg/RP0nRuCm48Lt_uhh4jaDGsPefT068bGH48IbYmNcKAm2Zcn3rVxwufIXhJgTtjsxUvzkRsojxJJqvCvUS40mrrfWNpVaDY2-KU8DBGrZdfoYimTbzlp23ySYJ3r8yhp8pXcl3ZaBYD_8iQK6zOoQVwzvG8tLax3WTDss-fvjLeTJ7XZvYQgZFthCdPBm2Bk0l5zaZq3N8k41JbNAqwWimsDKCWRI0Fr0muYlKSoTLiDVW6RgEbo2dgeuZWfU9g-H1xj_mKGlSRGhsCOLxl0SptOh0u9ZUoCXFfsLR9debS7VUOlNM7Kb-yMxFFKB
  • There are many functions used in socket. We can classify those functions based on functionalities.

    • Create Socket

    • Bind Socket

    • Recvfrom data_packet

    • Close socket

  • socket() is used to create a new socket. For example,

server_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  • bind() is used to associate the socket with a specific address and port. For example,

ret = bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr));
  • recvfrom is commonly used with UDP sockets, where communication is connectionless. it provides information about the source (sender) of the data, including the sender’s IP address and port number. For example,

len = recvfrom(server_socket, buffer, BUFFER_SIZE, 0, (struct sockaddr*)&client_addr, &addr_size);
  • close is used to close the socket To free up system resources associated with the socket. For example,

(void)close(server_socket);
  • See the full program below,

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define BUFFER_SIZE 1024
#define NUM_MESSAGES 10

void validate_convert_port(
char *port_str,
struct sockaddr_in *sock_addr)
{
  int port;

  if (port_str == NULL) {
   perror("Invalid port_str\n");
   exit(EXIT_FAILURE);
  }

  if (sock_addr == NULL) {
   perror("Invalid sock_addr\n");
   exit(EXIT_FAILURE);
  }

  port = atoi(port_str);

  if (port == 0) {
    perror("Invalid port\n");
    exit(EXIT_FAILURE);
  }

  sock_addr->sin_port = htons(
  (uint16_t)port);
  printf("Port: %d\n",
  ntohs(sock_addr->sin_port));
}

int main(int argc, char *argv[]) 
{
  int server_socket;
  int i, ret;
  struct sockaddr_in 
  server_addr, 
  client_addr;
  socklen_t addr_size = sizeof(
  client_addr);
  char buffer[BUFFER_SIZE];

  if (argc != 2) {
    printf("%s <port-number>", 
    argv[0]);
    return -1;
  }

  server_socket = socket(AF_INET,
                  SOCK_DGRAM,
                  IPPROTO_UDP);

  if (server_socket < 0) {
    perror("Socket failed");
    return -2;
  }

  server_addr.sin_family = AF_INET;
  server_addr.sin_addr.s_addr = 
  INADDR_ANY;
  validate_convert_port(argv[1], 
  &server_addr);

  ret = bind(server_socket,
  (struct sockaddr *)&server_addr,
  sizeof(server_addr));

  if (ret < 0) {
    perror("Bind failed");
    (void)close(server_socket);
    return -3;
  }

  i = 0;
  while (i < NUM_MESSAGES) { 
    memset(buffer, 0, 
    sizeof(buffer));

    ret = recvfrom(server_socket, 
    buffer,
    BUFFER_SIZE, 0,
    (struct sockaddr *)&client_addr,
    &addr_size);

    if (ret < 0) {
      perror("recvfrom");
      (void)close(server_socket);
      return -4;
    }

    printf("Received: %s\n", 
    buffer);
    ++i;
  }

  (void)close(server_socket);

  return 0;
}

 1$ gcc -o server server.c
 2
 3$ sudo ./server 8080
 4
 5Port: 8080
 6Received: Message 1 from server!
 7Received: Message 2 from server!
 8Received: Message 3 from server!
 9Received: Message 4 from server!
10Received: Message 5 from server!
11Received: Message 6 from server!
12Received: Message 7 from server!
13Received: Message 8 from server!
14Received: Message 9 from server!
15Received: Message 10 from server!
https://www.plantuml.com/plantuml/svg/LP31Ri8m44Jl_ehjfRAB3voJ8X6LW10AYGYShU1iX8M9aTS1jLzV1pYqfzNCFksCTawXyM6uMFOMJdX1e6kZqJP7zbYmX9m-O-3PKgst-Lv2NNvjr6Arome9wwhQbVjI7HQLI5bYO0RJbDrFnYBmrp3m2Tj3eOgyhhDLNWi1Xe1_8ubu7FisEAwjmJwePvI4uz1rw2LGy1Px_fH2mbG2ZzwW0uneqxR-GxmJ-XjwDIe9GEO7NSV_c6AiDfcObCMmHocMy9iphT3M4VuFZom5TsNpoCQd_08=
  • There are many functions used in socket. We can classify those functions based on functionalities.

    • Create Socket

    • Sendto data_packet

    • Close socket

  • socket is used to create a new socket. For example,

client_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  • sendto is used to send the encoded message to the specified server address and port using a UDP socket. For example,

ret = sendto(client_socket, buffer, strlen(buffer), 0, (struct sockaddr*)&server_addr, sizeof(server_addr));
  • close is used to close the socket To free up system resources associated with the socket. For example,

(void)close(client_socket);
  • See the full program below,

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define BUFFER_SIZE 1024
#define NUM_MESSAGES 10

void validate_convert_port(
char *port_str,
struct sockaddr_in *sock_addr)
{
  int port;

  if (port_str == NULL) {
     perror("Invalid port_str\n");
     exit(EXIT_FAILURE);
 }

 if (sock_addr == NULL) {
     perror("Invalid sock_addr\n");
     exit(EXIT_FAILURE);
 }
  
 port = atoi(port_str);

 if (port == 0) {
   perror("Invalid port\n");
   exit(EXIT_FAILURE);
 }

 sock_addr->sin_port = htons(
 (uint16_t)port);
 printf("Port: %d\n",
 ntohs(sock_addr->sin_port));
}

void validate_convert_addr(
char *ip_str,
struct sockaddr_in *sock_addr)
{
  if (ip_str == NULL) {
     perror("Invalid ip_str\n");
     exit(EXIT_FAILURE);
 }

 if (sock_addr == NULL) {
     perror("Invalid sock_addr\n");
     exit(EXIT_FAILURE);
 }

 printf("IP Address: %s\n", ip_str);

 if (inet_pton(AF_INET, ip_str,
 &(sock_addr->sin_addr)) <= 0) {
    perror("Invalid address\n");
    exit(EXIT_FAILURE);
  }
}

int main(int argc, char *argv[]) 
{
  int client_socket;
  int i, ret;
  struct sockaddr_in 
  server_addr;
  char buffer[BUFFER_SIZE] = "Hello from client!";
  socklen_t addr_size = sizeof(
  server_addr);

  if (argc != 3) {
    printf("%s<port-number><ip-addr>\n",
    argv[0]);
    return -1;
  }

  client_socket = socket(AF_INET,
                  SOCK_DGRAM,
                  IPPROTO_UDP);

  if (client_socket < 0) {
    perror("Socket failed");
    return -2;
  }

  server_addr.sin_family = AF_INET;
  validate_convert_port(argv[1], 
  &server_addr);
  validate_convert_addr(argv[2], 
  &server_addr);

  i = 0;
  while (i < NUM_MESSAGES) {  
   snprintf(buffer, sizeof(buffer),
        "Message %d from server!",
        i + 1);

   ret = sendto(client_socket, buffer,
   strlen(buffer), 0,
   (struct sockaddr *)&server_addr,
   sizeof(server_addr));

   if (ret < 0) {
     perror("sendto");
     (void)close(client_socket);
     return -3;
   }

   printf("Message %d sent: %s\n",
   i + 1, buffer);
   ++i;
  }

  (void)close(client_socket);

  return 0;
}

 1$ gcc -o client client.c
 2
 3$ sudo ./client 8080 127.0.0.1
 4
 5Port: 8088
 6IP Address: 127.0.0.1
 7Message 1 sent: Message 1 from server!
 8Message 2 sent: Message 2 from server!
 9Message 3 sent: Message 3 from server!
10Message 4 sent: Message 4 from server!
11Message 5 sent: Message 5 from server!
12Message 6 sent: Message 6 from server!
13Message 7 sent: Message 7 from server!
14Message 8 sent: Message 8 from server!
15Message 9 sent: Message 9 from server!
16Message 10 sent: Message 10 from server!

$ sudo ./server 8080 127.0.0.1

$ sudo ./client 8080 127.0.0.1

program to run with elevated privileges, listen on port 8080, and bind to the loopback address 127.0.0.1.

<port_number> <ip_address> decided by the user based on the connection.

Default Domain:

By default, the socket is configured to work in the AF_INET domain, handling all types of network data.

Additional Domain Support:

We expand the socket’s capabilities to also function in the PF_INET domain, allowing it to operate similarly to AF_INET.

Socket Creation:

We set up a network connection point known as a socket using socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP).

Working Scenario:

Despite the change in domain to PF_INET, the socket continues to operate the same way, handling general network data.

Socket API

Learning

socket

Create a new socket

bind

Associate the socket with a specific address and port

recvfrom

It provides information about the source (sender) of the data, including the sender’s IP address and port number.

sendto

Send the encoded message to the specified server address and port using a UDP socket.