Basic example raw af inet udp server and client

  • In this program, you are going to learn

  • How to create 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_RAW, IPPROTO_UDP) do?

When would I use SOCK_RAW sockets with IPPROTO_UDP?

Can SOCK_RAW sockets be used for regular UDP communication?

What is the difference between IPPROTO_UDP and SOCK_RAW for UDP communication?

What are common issues when working with raw UDP sockets?

How do I handle errors when using raw UDP sockets?

Can raw UDP sockets be used for both sending and receiving data?

Why is it important to check the return value of sendto() and recvfrom() in socket programming?

https://www.plantuml.com/plantuml/svg/LO-zZi8m48HxFyNI81jSS2qq87uaT1A9E4vNMewz9jObSMHlAExfpqQYe1jziwEPtIRIaQQ-OpDgiKT8epROwOOz3RPEmVmYyTr9dI_7cuIlQl-fhhiV2UUwlbQtIdqVQh5XwuZcuMBeUKaePoKKqapEOPGy-JyCZYUAao7mOskZW2Myuya-USOKEnmAziDTMKrQB3-4X9M4rsrfqTR6XJ2Tnu6AbZ3FiJkrPGz_16-p6HA-9cMSA8niYuFDB_y3
  • There are many functions used in socket. We can classify those functions based on functionalities.

    • Create Socket

    • Recvfrom data_packet

    • Close socket

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

sock_fd = socket(AF_INET, SOCK_RAW, IPPROTO_UDP);
  • recvfrom is commonly used with 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,

ret = recvfrom(sock_fd, recvbuffer,(sizeof(struct iphdr) + sizeof(struct udphdr)+ strlen(string_data)+1), 0, (struct sockaddr*)clientaddr, &length);
  • close is used to close the socket To free up system resources associated with the socket. For example,

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

#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <linux/udp.h> /* UDP Header */
#include <arpa/inet.h>
#include <unistd.h>
#include <signal.h>
#include <linux/ip.h>

struct sockaddr_in 
*clientaddr = NULL;
int sock_fd;
int SERVPORT=20000;
int DESTPORT=20001;

struct pseudo_iphdr {
  unsigned int source_ip_addr;
  unsigned int dest_ip_addr;
  unsigned char fixed;
  unsigned char protocol;
  unsigned short udp_len;
};

unsigned short in_cksum (
uint16_t * addr, int len)
{
  int nleft = len;
  unsigned int sum = 0;
  unsigned short *w = addr;
  unsigned short answer = 0;

  while (nleft > 1) {
    sum += *w++;
    nleft -= 2;
  }

  if (nleft == 1) {
    *(unsigned char *) (&answer) = 
    * (unsigned char *) w;
    sum += answer;
  }

  sum = (sum >> 16) + 
  (sum & 0xffff); 
  sum += (sum >> 16); 
  answer = (unsigned short) ~sum; 
  return (answer);
}

void interrupt_handler (
int signum)
{
  (void)close(sock_fd);
  free(clientaddr);
  exit(0);
}

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);
  }
}

void main (int argc, char *argv[]) 
{
  socklen_t length;
  char buffer[1024] = {0};
  unsigned char 
  recvbuffer[1024] = {0};
  char *string = 
  "Hello client\n";
  struct udphdr *udp_hdr = NULL;
  char *string_data = NULL;
  char *recv_string_data = NULL;
  char *csum_buffer = NULL;
  struct pseudo_iphdr 
  csum_hdr;
  int ret;
 
  signal (SIGINT, 
  interrupt_handler);
  signal (SIGTERM, 
  interrupt_handler);

  if (argc != 2) {
   printf("%s<ip-addr>\n",
   argv[0]);
   exit(EXIT_FAILURE);
  }

  sock_fd = socket(AF_INET, 
               SOCK_RAW, 
               IPPROTO_UDP);
  
  if (sock_fd < 0) {
    printf("create a socket\n");
    exit(0);
  }

  clientaddr = (struct sockaddr_in *)malloc(
  sizeof(struct sockaddr_in));

  if (clientaddr == NULL) {
    printf("allocate memory\n");
    goto end;
  }

  clientaddr->sin_family = AF_INET;
  clientaddr->sin_port = 
  htons(DESTPORT);
  validate_convert_addr(argv[1],
  clientaddr);

  memset(buffer, 0, 
  sizeof(buffer));

  string_data = (char *) 
  (buffer + sizeof(struct udphdr));
  strncpy(string_data, 
  string, strlen(string));


  udp_hdr = (struct udphdr *)buffer;

  udp_hdr->source = htons(SERVPORT);
  udp_hdr->dest = htons(DESTPORT);
  udp_hdr->len = htons(
  sizeof(struct udphdr));

  csum_buffer = (char *)calloc((
  sizeof(struct pseudo_iphdr) + 
  sizeof(struct udphdr) + 
  strlen(string_data)), sizeof(char));
  
 if (csum_buffer == NULL) {
    printf("allocate csum buffer\n");
    goto end1;
  }

  csum_hdr.source_ip_addr = inet_addr("127.0.0.1");
  csum_hdr.dest_ip_addr = inet_addr("127.0.0.1");
  csum_hdr.fixed = 0;
  csum_hdr.protocol = IPPROTO_UDP; 
  csum_hdr.udp_len = htons(
  sizeof(struct udphdr) + 
  strlen(string_data) + 1);

  memcpy(csum_buffer, 
  (char *)&csum_hdr, 
  sizeof(struct pseudo_iphdr));
  
  memcpy(csum_buffer + 
  sizeof(struct pseudo_iphdr), buffer, 
  (sizeof(struct udphdr) + 
  strlen(string_data) + 1));

  udp_hdr->check = (in_cksum(
  (unsigned short *) csum_buffer,
  (sizeof(struct pseudo_iphdr)+ 
  sizeof(struct udphdr) + 
  strlen(string_data) + 1)));

  printf("checksum is %x\n", 
  udp_hdr->check);
  free (csum_buffer);

  memset(recvbuffer, 0, 
  sizeof(recvbuffer));
  
  ret = recvfrom(sock_fd, 
  recvbuffer,(sizeof(struct iphdr) + 
  sizeof(struct udphdr)+
  strlen(string_data)+1), 0,    
  (struct sockaddr *)clientaddr, 
  &length);
  
 if (ret < 0) {
    printf("recv Message\n");
    goto end1;
  }

  udp_hdr = (struct udphdr *)
  (recvbuffer + 
  sizeof (struct iphdr));
  
 recv_string_data = (char *) 
 (recvbuffer + sizeof (struct iphdr) +
 sizeof (struct udphdr));
  
 if (SERVPORT == 
 ntohs(udp_hdr->source)) {
    printf("Received :%s\n", 
    recv_string_data);
  }

end1:
  free (clientaddr);
end:
  (void)close(sock_fd);
  return;
}

$ gcc -o server server.c

$ sudo ./server 127.0.0.1

IP Address: 127.0.0.1
checksum is 53fc
Received :Hello server
https://www.plantuml.com/plantuml/svg/LOyx3y8m38Jt_Wgp9P01LbX0F2I4HAi2Oen2uq94crI9oy2l9-4niDbtdq_dUI3bgM-RR40tR152fofir2Lx6zaqkEgEn1ORkTslZm8E-N8doyLPmBOeoloOozEguBC8ejNaME9hBU3IrpLw0IoO9xgQ1V9zHT3hxgOz7q7S6xH9DlOgjIB5HnCkO9nEFcoAKbhx8QyQWvRIBE0_xyT8OtbgmHxEwCYxWDygKGtakcmU-yK_Nm==
  • 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,

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

ret = sendto(sockfd, buffer, (sizeof(struct udphdr)+ strlen(string_data)+1), 0, (struct sockaddr*)clientaddr, sizeof(struct sockaddr_in));
  • close is used to close the socket To free up system resources associated with the socket. For example,

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

#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <linux/udp.h> /* UDP Header */
#include <arpa/inet.h>
#include <unistd.h>
#include <signal.h>
#include <linux/ip.h>
#include <poll.h>

struct sockaddr_in 
*clientaddr = NULL;
int sockfd;
int SERVPORT=20000;
int DESTPORT=20001;

struct pseudo_iphdr {
  unsigned int source_ip_addr;
  unsigned int dest_ip_addr;
  unsigned char fixed;
  unsigned char protocol;
  unsigned short udp_len;
};

unsigned short in_cksum (
uint16_t * addr, int len)
{
  int nleft = len;
  unsigned int sum = 0;
  unsigned short *w = addr;
  unsigned short answer = 0;

  while (nleft > 1) {
    sum += *w++;
    nleft -= 2;
  }

  if (nleft == 1) {
    *(unsigned char *) (&answer) = * 
    (unsigned char *) w;
    sum += answer;
  }

  sum = (sum >> 16) + 
  (sum & 0xffff); 
  sum += (sum >> 16); 
  answer = (unsigned short) ~sum; 
  return (answer);
}

void interrupt_handler (
int signum)
{
  (void)close(sockfd);
  free(clientaddr);
  exit(0);
}

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[])
{
   socklen_t length;
   char buffer[1024] = {0};
   unsigned char recvbuffer[1024] = 
   {0};
   char *string = 
   "Hello server\n";
   struct udphdr *udp_hdr = NULL;
   char *string_data = NULL;
   char *recv_string_data = NULL;
   char *csum_buffer = NULL;
   struct pseudo_iphdr csum_hdr;
   int ret;

   signal (SIGINT, 
   interrupt_handler);
   signal (SIGTERM, 
   interrupt_handler);

   if (argc != 2) {
    printf("%s<ip-addr>\n",
    argv[0]);
    exit(EXIT_FAILURE);
   }

   sockfd = socket(AF_INET, 
            SOCK_RAW, 
            IPPROTO_UDP);

   if (sockfd < 0) {
      printf("create a socket\n");
      exit(0);
   }

   clientaddr = (struct sockaddr_in *)
   malloc(sizeof(struct sockaddr_in));

   if (clientaddr == NULL) {
      printf("allocate memory\n");
      goto end;
   }

   clientaddr->sin_family = AF_INET;
   clientaddr->sin_port = 
   htons(DESTPORT);
   validate_convert_addr(argv[1],
   clientaddr);

   memset(buffer, 0, 
   sizeof(buffer));

   string_data = (char *) 
   (buffer + sizeof(struct udphdr));
   strncpy(string_data, 
   string, strlen(string));

   udp_hdr = (struct udphdr *)buffer;

   udp_hdr->source = htons(SERVPORT);
   udp_hdr->dest = htons(DESTPORT);
   udp_hdr->len = htons(
   sizeof(struct udphdr));

   csum_buffer = (char *)calloc(
   (sizeof(struct pseudo_iphdr) + 
   sizeof(struct udphdr) + 
   strlen(string_data)), sizeof(char));
      
   if (csum_buffer == NULL) {
       printf("allocate csum buffer\n");
       goto end1;
   }

   csum_hdr.source_ip_addr = 
   inet_addr("127.0.0.1");
   csum_hdr.dest_ip_addr = 
   inet_addr("127.0.0.1");
   csum_hdr.fixed = 0;
   csum_hdr.protocol = IPPROTO_UDP; /* UDP protocol */
   csum_hdr.udp_len = htons(
   sizeof(struct udphdr) + 
   strlen(string_data) + 1);

   memcpy(csum_buffer, 
   (char *)&csum_hdr, 
   sizeof(struct pseudo_iphdr));
   memcpy(csum_buffer + 
   sizeof(struct pseudo_iphdr), 
   buffer, (sizeof(struct udphdr) + 
   strlen(string_data) + 1));

   udp_hdr->check = (in_cksum(
   (unsigned short *) csum_buffer,
   (sizeof(struct pseudo_iphdr)+ 
   sizeof(struct udphdr) + 
   strlen(string_data) + 1)));

   printf("checksum is %x\n",
   udp_hdr->check);
   free (csum_buffer);

   ret = sendto(sockfd, buffer,
   (sizeof(struct udphdr)+
   strlen(string_data)+1), 0,
   (struct sockaddr *)clientaddr, 
   sizeof(struct sockaddr_in));
        
   if (ret < 0) {
      perror("sendto");
      goto end1;
   }
   printf("sent message\n");

end1:
    free (clientaddr);
end:
    (void)close (sockfd);
    return 0;
}
$ gcc -o client client.c

$ sudo ./client 127.0.0.1

IP Address: 127.0.0.1
checksum is 4bec
sent message
https://www.plantuml.com/plantuml/svg/LP11JyCm38Nl-HNcWXAQmxYs8As2WYQqjLetSOoonbqZsgPAqY7uzIGLE-naw_EpthFNpalhvw4dTxx30S5Dii5UdiWo8AappHTwch-9pQuuSAZBbm-nppyvRAfgNnvASNojM4PI3S-moiXtfti4-byqFC7kk1NRegxpzw9c3BG3-eEEaTHYSscj6MZq4AtY4CbfRbkqd3hzYwQbpjkvyQ2dJba62TpYMIqyO6zx72FMuraewILB7Xc75OUhDhf8fUm3QtgDeuyzX_kmTlPTl219T4PmL4jsajABqIfeZSDhmg1otana7LJXPty=
  • There are many functions used in socket. We can classify those functions based on functionalities.

    • Create Socket

    • Recvfrom data_packet

    • Close socket

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

sock_fd = socket(AF_INET, SOCK_RAW, IPPROTO_UDP);
  • recvfrom is commonly used with 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,

ret = recvfrom(sock_fd, recvbuffer,(sizeof(struct iphdr) + sizeof(struct udphdr)+ strlen(string_data)+1), 0, (struct sockaddr*)clientaddr, &length);
  • close is used to close the socket To free up system resources associated with the socket. For example,

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

#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <linux/udp.h> /* UDP Header */
#include <arpa/inet.h>
#include <unistd.h>
#include <signal.h>
#include <linux/ip.h>

#define NUM_MESSAGES 10

struct sockaddr_in 
*clientaddr = NULL;
int sock_fd;
int SERVPORT=20000;
int DESTPORT=20001;

struct pseudo_iphdr {
  unsigned int source_ip_addr;
  unsigned int dest_ip_addr;
  unsigned char fixed;
  unsigned char protocol;
  unsigned short udp_len;
};

unsigned short in_cksum (
uint16_t * addr, int len)
{
  int nleft = len;
  unsigned int sum = 0;
  unsigned short *w = addr;
  unsigned short answer = 0;

  while (nleft > 1) {
    sum += *w++;
    nleft -= 2;
  }

  if (nleft == 1) {
    *(unsigned char *) (&answer) = 
    * (unsigned char *) w;
    sum += answer;
  }

  sum = (sum >> 16) + 
  (sum & 0xffff); 
  sum += (sum >> 16); 
  answer = (unsigned short) ~sum; 
  return (answer);
}

void interrupt_handler (
int signum)
{
  (void)close(sock_fd);
  free(clientaddr);
  exit(0);
}

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);
  }
}

void main (int argc, char *argv[]) 
{
  socklen_t length;
  char buffer[1024] = {0};
  unsigned char 
  recvbuffer[1024] = {0};
  char *string = 
  "Hello client\n";
  struct udphdr *udp_hdr = NULL;
  char *string_data = NULL;
  char *recv_string_data = NULL;
  char *csum_buffer = NULL;
  struct pseudo_iphdr 
  csum_hdr;
  int ret, i;
 
  signal (SIGINT, 
  interrupt_handler);
  signal (SIGTERM, 
  interrupt_handler);

  if (argc != 2) {
   printf("%s<ip-addr>\n",
   argv[0]);
   exit(EXIT_FAILURE);
  }

  sock_fd = socket(AF_INET, 
               SOCK_RAW, 
               IPPROTO_UDP);
  
  if (sock_fd < 0) {
    printf("create a socket\n");
    exit(0);
  }

  clientaddr = (struct sockaddr_in *)malloc(
  sizeof(struct sockaddr_in));

  if (clientaddr == NULL) {
    printf("allocate memory\n");
    goto end;
  }

  clientaddr->sin_family = AF_INET;
  clientaddr->sin_port = 
  htons(DESTPORT);
  validate_convert_addr(argv[1],
  clientaddr);

  memset(buffer, 0, 
  sizeof(buffer));

  string_data = (char *) 
  (buffer + sizeof(struct udphdr));
  strncpy(string_data, 
  string, strlen(string));

  udp_hdr = (struct udphdr *)buffer;

  udp_hdr->source = htons(SERVPORT);
  udp_hdr->dest = htons(DESTPORT);
  udp_hdr->len = htons(
  sizeof(struct udphdr));

  csum_buffer = (char *)calloc((
  sizeof(struct pseudo_iphdr) + 
  sizeof(struct udphdr) + 
  strlen(string_data)), sizeof(char));
  
 if (csum_buffer == NULL) {
    printf("allocate csum buffer\n");
    goto end1;
  }

  csum_hdr.source_ip_addr = 
  inet_addr("127.0.0.1");
  csum_hdr.dest_ip_addr = 
  inet_addr("127.0.0.1");
  csum_hdr.fixed = 0;
  csum_hdr.protocol = IPPROTO_UDP; 
  csum_hdr.udp_len = htons(
  sizeof(struct udphdr) + 
  strlen(string_data) + 1);

  memcpy(csum_buffer, 
  (char *)&csum_hdr, 
  sizeof(struct pseudo_iphdr));
  memcpy(csum_buffer + 
  sizeof(struct pseudo_iphdr), buffer, 
  (sizeof(struct udphdr) + 
  strlen(string_data) + 1));

  udp_hdr->check = (in_cksum(
  (unsigned short *) csum_buffer,
  (sizeof(struct pseudo_iphdr)+ 
  sizeof(struct udphdr) + 
  strlen(string_data) + 1)));

  printf("checksum is %x\n", 
  udp_hdr->check);
  free (csum_buffer);

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

    ret = recvfrom(sock_fd, 
    recvbuffer,(sizeof(struct iphdr) + 
    sizeof(struct udphdr)+
    strlen(string_data)+1), 0,    
    (struct sockaddr *)clientaddr, 
    &length);
  
   if (ret < 0) {
     printf("recv Message\n");
     goto end1;
   }

   udp_hdr = (struct udphdr *)
   (recvbuffer + 
   sizeof (struct iphdr));
  
   recv_string_data = (char *) 
   (recvbuffer + sizeof (struct iphdr) +
   sizeof (struct udphdr));
  
   if (SERVPORT == 
   ntohs(udp_hdr->source)) {
     printf("Received :%s\n", 
     recv_string_data);
   }
   ++i;
  }
end1:
  free (clientaddr);
end:
  (void)close(sock_fd);
  return;
}

$ gcc -o server server.c

$ sudo ./server 127.0.0.1

IP Address: 127.0.0.1
checksum is 53fc
Received :Hello server

Received :Hello server

Received :Hello server

Received :Hello server

Received :Hello server

Received :Hello server

Received :Hello server

Received :Hello server

Received :Hello server

Received :Hello server
https://www.plantuml.com/plantuml/svg/LP0zJyCm48Pt_ufZiuc7iYOWDO8KLQXDrBHYjDpuGgowSMGx8FZrsAKCdUxhlVSUtT87wS9yDkGk37X6y9FiqCWZkGn8xcrtma3BbLXlgps7jdv-4xlodSEwQNRrlXQ7buOL9DVm18k2V0tQ8D1hqF08syD6RAgsBL-hbZ7G7kWtUXQjSLJ1qdIXLnoESz-Zuq2z_a7RKn_St0MOrJGenpA8jS4njVNu8PGCacKFZCCYhVnfavLKojsppcWSGyevtFhzQuGUMUBECbsGI78X9Zdzj5h5TUlnIXP5FjY9BACeFkeN
  • 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,

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

ret = sendto(sockfd, buffer, (sizeof(struct udphdr)+ strlen(string_data)+1), 0, (struct sockaddr*)clientaddr, sizeof(struct sockaddr_in));
  • close is used to close the socket To free up system resources associated with the socket. For example,

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

#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <linux/udp.h> /* UDP Header */
#include <arpa/inet.h>
#include <unistd.h>
#include <signal.h>
#include <linux/ip.h>

#define NUM_MESSAGES 10

struct sockaddr_in 
*clientaddr = NULL;
int sockfd;
int SERVPORT=20000;
int DESTPORT=20001;

struct pseudo_iphdr {
  unsigned int source_ip_addr;
  unsigned int dest_ip_addr;
  unsigned char fixed;
  unsigned char protocol;
  unsigned short udp_len;
};

unsigned short in_cksum (
uint16_t * addr, int len)
{
  int nleft = len;
  unsigned int sum = 0;
  unsigned short *w = addr;
  unsigned short answer = 0;

  while (nleft > 1) {
    sum += *w++;
    nleft -= 2;
  }

  if (nleft == 1) {
    *(unsigned char *) (&answer) = * 
    (unsigned char *) w;
    sum += answer;
  }

  sum = (sum >> 16) + 
  (sum & 0xffff); 
  sum += (sum >> 16); 
  answer = (unsigned short) ~sum; 
  return (answer);
}

void interrupt_handler (
int signum)
{
  (void)close(sockfd);
  free(clientaddr);
  exit(0);
}

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[])
{
   socklen_t length; 
   char buffer[1024] = {0};
   unsigned char recvbuffer[1024] = 
   {0};
   char *string = 
   "Hello server\n";
   struct udphdr *udp_hdr = NULL;
   char *string_data = NULL;
   char *recv_string_data = NULL;
   char *csum_buffer = NULL;
   struct pseudo_iphdr csum_hdr;
   int ret, i;

   signal (SIGINT, 
   interrupt_handler);
   signal (SIGTERM, 
   interrupt_handler);

   if (argc != 2) {
    printf("%s<ip-addr>\n",
    argv[0]);
    exit(EXIT_FAILURE);
   }

   sockfd = socket(AF_INET, 
            SOCK_RAW, 
            IPPROTO_UDP);

   if (sockfd < 0) {
      printf("create a socket\n");
      exit(0);
   }

   clientaddr = (struct sockaddr_in *)
   malloc(sizeof(struct sockaddr_in));

   if (clientaddr == NULL) {
      printf("allocate memory\n");
      goto end;
   }

   clientaddr->sin_family = AF_INET;
   clientaddr->sin_port = 
   htons(DESTPORT);
   validate_convert_addr(argv[1],
   clientaddr);

   memset(buffer, 0, 
   sizeof(buffer));

   string_data = (char *) 
   (buffer + sizeof(struct udphdr));
   strncpy(string_data, 
   string, strlen(string));

   udp_hdr = (struct udphdr *)buffer;

   udp_hdr->source = htons(SERVPORT);
   udp_hdr->dest = htons(DESTPORT);
   udp_hdr->len = htons(
   sizeof(struct udphdr));

   csum_buffer = (char *)calloc(
   (sizeof(struct pseudo_iphdr) + 
   sizeof(struct udphdr) + 
   strlen(string_data)), sizeof(char));
      
   if (csum_buffer == NULL) {
       printf("allocate csum buffer\n");
       goto end1;
   }

   csum_hdr.source_ip_addr = 
   inet_addr("127.0.0.1");
   csum_hdr.dest_ip_addr = 
   inet_addr("127.0.0.1");
   csum_hdr.fixed = 0;
   csum_hdr.protocol = IPPROTO_UDP; /* UDP protocol */
   csum_hdr.udp_len = htons(
   sizeof(struct udphdr) + 
   strlen(string_data) + 1);

   memcpy(csum_buffer, 
   (char *)&csum_hdr, 
   sizeof(struct pseudo_iphdr));
   memcpy(csum_buffer + 
   sizeof(struct pseudo_iphdr), 
   buffer, (sizeof(struct udphdr) + 
   strlen(string_data) + 1));

   udp_hdr->check = (in_cksum(
   (unsigned short *) csum_buffer,
   (sizeof(struct pseudo_iphdr)+ 
   sizeof(struct udphdr) + 
   strlen(string_data) + 1)));

   printf("checksum is %x\n",
   udp_hdr->check);
   free (csum_buffer);

   i = 0;
   while (i < NUM_MESSAGES) {
      ret = sendto(sockfd, buffer,
      (sizeof(struct udphdr)+
      strlen(string_data)+1), 0,
      (struct sockaddr *)clientaddr, 
      sizeof(struct sockaddr_in));
        
      if (ret == -1) {
          printf("send Message\n");
          goto end1;
      }
      printf("SentMessage\n");

      ++i;
   }

end1:
    free (clientaddr);
end:
    (void)close (sockfd);
    return 0;
}
$ gcc -o client client.c

$ sudo ./client 127.0.0.1

IP Address: 127.0.0.1
checksum is 4bec
SentMessage
SentMessage
SentMessage
SentMessage
SentMessage
SentMessage
SentMessage
SentMessage
SentMessage
SentMessage

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_RAW, 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

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 socket.