IPV4 RAW AF INET ICMP server client program with Epoll system call

Let us answer few basic questions in this socket

What does socket(AF_INET, SOCK_RAW, IPPROTO_ICMP) do?

Why use AF_INET as the address family?

What is the purpose of SOCK_RAW in the socket type?

Why specify IPPROTO_ICMP as the protocol?

Can this socket send ICMP packets as well?

How does this socket differ from a standard UDP or TCP socket?

Is error checking needed after creating the socket?

Can this socket be used for other protocols besides ICMP?

Why close the socket after processing?

How is the source IP address extracted from the received packet?

Can this socket receive ICMP messages from any source?

Why cast to struct iphdr and struct icmphdr in packet processing?

What is the primary purpose of the epoll system call?

What types of file descriptors can be monitored using epoll?

What data structure is used by epoll to store events?

How do you handle errors when using the epoll system call?

How does epoll handle a set of file descriptors with different states (e.g., reading, writing, exception)?

How does epoll Checking Ready File Descriptors?

What does it mean if epoll returns 0?

https://www.plantuml.com/plantuml/svg/XL9RQy8m57xlhpXxaMHcegyEmL8xa5KjsbrWZ53JKonBcvB4olRhbrfrSozxIKxEET-5ZqoDJRNTbzAxiJii4KoT2fJfrZiElB5HuWCjyH_uV1ac33Qhu96l_HS6ypXUhv8LdmUBcDvxOwoLb3pFO09TAJIc5aTa-3CLLfBp7eCmNaKH3vA8-xCP0uEwGSqxHGOzRB2o3dlO5HA172yoeXGA0-GJ3Jsp7jB2_g8zuWo3XV_Am-TmcMmOt8qSKP43wOPlm_T1bjfqqDgTN2jJS4bK9mK066iKJQvLIVuOtExp7BNpNNoXoadtf0o639PFKTITJhRbC5XbLlt3OApU2mk5AEjTfYdqmNKaLgIrsX6VTrg6DClqBUrbQ2nlwmlFfKETEahZmgiKzPo58c_FKw11iexwmgL86bLaL4XbyDgXWnkhQc_gGEwFV0C=
  • There are many functions used in socket. We can classify those functions based on functionalities.

    • Create Socket

    • Epoll create1

    • Epoll_ctl

    • Epoll_wait

    • Recvfrom data_packet

    • Sendto data_packet

    • Close socket

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

server_socket = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
  • epoll_create1() creating an epoll instance using epoll_create1, The size parameter is an advisory hint for the kernel regarding the number of file descriptors expected to be monitored, For example,

epoll_fd = epoll_create1(0);
  • epoll_ctl() After creating an epoll instance, file descriptors are added to it using epoll_ctl, For example,

ret = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, server_socket, &event);
  • epoll_wait() The application then enters a loop where it waits for events using epoll_wait, For example,

ready_fds = epoll_wait(epoll_fd, events, MAX_EVENTS, -1);
  • 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(server_socket, buffer, sizeof(buffer), 0, NULL, NULL);
  • sendto is used to send the encoded message to the specified server address and port using a socket. For example,

ret = sendto(server_socket, buffer, sizeof(struct icmphdr) + strlen(data), 0, (struct sockaddr*)&dest_addr, sizeof(dest_addr));
  • 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>
#include <netinet/ip_icmp.h>
#include <netinet/ip.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/epoll.h>

#define BUFFER_SIZE 1024
#define MAX_EVENTS 2

int epoll_fd = -1;
int server_socket = -1;

static void sigint_handler(int signo)
{
  (void)close(server_socket);
  sleep(2);
  (void)printf("Caught sigINT!\n");
  exit(EXIT_SUCCESS);
}

void register_signal_handler(
int signum,
void (*handler)(int))
{
  if (signal(signum, handler) ==
  SIG_ERR) {
     printf("Cannot handle signal\n");
     exit(EXIT_FAILURE);
  }
}

void send_icmp_message(
int client_socket, 
const char *data) 
{
  char buffer[BUFFER_SIZE];
  struct sockaddr_in 
  dest_addr;
  int ret;
  struct icmphdr 
  *icmp_header;

  snprintf(buffer + 
  sizeof(struct icmphdr), 
  sizeof(buffer) - 
  sizeof(struct icmphdr), "%s",
  data);
      
  icmp_header = 
  (struct icmphdr *)buffer;
  icmp_header->type = ICMP_ECHO;
  icmp_header->code = 0;
  icmp_header->checksum = 0;
  icmp_header->un.echo.id = 0;
  icmp_header->un.echo.sequence = 0;

  ret = sendto(client_socket, 
  buffer, sizeof(struct icmphdr) + 
  strlen(data), 0,
  (struct sockaddr *)&dest_addr, 
  sizeof(dest_addr));
        
  if (ret < 0) {
     perror("sendto");
     (void)close(client_socket);
     exit(EXIT_FAILURE);
   }
}

void process_icmp_message(
char *buffer, 
ssize_t length) 
{
    struct iphdr 
    *ip_header;    
    struct icmphdr 
    *icmp_header;
    char *original_data;

    icmp_header = (struct icmphdr *)
    (buffer + sizeof(struct iphdr));
    ip_header = (struct iphdr *)buffer;

    printf("Received ICMP message:\n");
    printf("Source IP: %s\n", 
    inet_ntoa(*(struct in_addr *)&
    (ip_header->saddr)));
    printf("Type: %d\n", icmp_header->type);
    printf("Code: %d\n", icmp_header->code);
    
    original_data = buffer + 
    sizeof(struct iphdr) + 
    sizeof(struct icmphdr);
    printf("Original Data: %s\n", 
    original_data);

}

int main() 
{
  int  ret;
  char buffer[BUFFER_SIZE];
  int ready_fds;
  struct epoll_event 
  events[MAX_EVENTS];
  struct epoll_event event;

  register_signal_handler(SIGINT,
  sigint_handler);
    
  server_socket = socket(AF_INET, 
                  SOCK_RAW, 
                  IPPROTO_ICMP);

  if (server_socket < 0) {
        perror("Socket failed");
        exit(EXIT_FAILURE);
  }

  fcntl(server_socket, 
  F_SETFL, 
  O_NONBLOCK);

  epoll_fd = epoll_create1(0);

  if (epoll_fd < 0) {
    perror("Epoll creation failed");
    exit(EXIT_FAILURE);
  }

  event.events = EPOLLIN;
  event.data.fd = server_socket;

  ret = epoll_ctl(epoll_fd,
  EPOLL_CTL_ADD, server_socket,
  &event);

  if (ret < 0) {
    perror("Epoll_ctl failed");
    (void)close(epoll_fd);
    (void)close(server_socket);
    exit(EXIT_FAILURE);
  }

  while (1) {
   ready_fds = epoll_wait(epoll_fd, 
   events, MAX_EVENTS, -1);

   if (ready_fds < 0) {
      perror("epoll_wait failed");
      break;     
   }

   if (events[0].data.fd == server_socket) {
     ret = recvfrom(server_socket, 
     buffer, sizeof(buffer), 0, NULL, NULL);
        
     if (ret < 0) {
       perror("recv");
       break;
     }

     process_icmp_message(buffer, ret);
     send_icmp_message(server_socket, 
     "Hello from server!");
     sleep(2);
   }
  }

  (void)close(server_socket);

  return 0;
}

$ gcc -o server server.c

$ sudo ./server

Received ICMP message:
Source IP: 127.0.0.1
Type: 8
Code: 0
Original Data: Hello from client!
Received ICMP message:
Source IP: 127.0.0.1
Type: 8
Code: 0
Original Data: Hello from server!
Received ICMP message:
Source IP: 127.0.0.1
Type: 8
Code: 0
Original Data: Hello from client!
Received ICMP message:
Source IP: 127.0.0.1
Type: 8
Code: 0
Original Data: Hello from server!
Received ICMP message:
Source IP: 127.0.0.1
Type: 8
Code: 0
Original Data: Hello from server!
Received ICMP message:
Source IP: 127.0.0.1
Type: 8
Code: 0
Original Data: Hello from client!
^CCaught sigINT!
https://www.plantuml.com/plantuml/svg/XL9RQy8m57xlhpXxaMHcegyEmL8xa5LRjBl06A6cfnYMDgM9olRhbrelsrwMXvDpF-VxagcnMMDtfV9kx1PB15Dd0bMsyOu1Rsoq-41B_0S-NuOfWtKSFFAL_y9WdYIhE8tvF5WazDuROwsLuaKE4-XKqM1cSKI6rwYmYfpp68H974KyI2FkpsOCX99OMTvDPD33lJDTxM4h5G8vNcH4AKW3v1CDTTjXbLjD_bHkTaM13GCZlr0NnDXc9on8KTRRlA7G1-THM94yinbbC6HmpcaxP7dUtD9UZiRoLh_qkNZe5T0Xa_O7ekFAXi72V-NXSxXCrmpkHYvT5a2wuDlmVT0E7hHCJNw3fk0UeJg1W_QC6nJxej7bFnWximEpV8gYJhh1g8pZhjBKSrJ9efKdFeDq5VM58v7ijSofKDhWxockt5XTUrDNvBx8Dm==
  • There are many functions used in socket. We can classify those functions based on functionalities.

    • Create Socket

    • Epoll create1

    • Epoll_ctl

    • Epoll_wait

    • Sendto data_packet

    • Recvfrom data_packet

    • Close socket

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

client_socket = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
  • epoll_create1() creating an epoll instance using epoll_create1, The size parameter is an advisory hint for the kernel regarding the number of file descriptors expected to be monitored, For example,

epoll_fd = epoll_create1(0);
  • epoll_ctl() After creating an epoll instance, file descriptors are added to it using epoll_ctl, For example,

ret = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client_socket, &event);
  • epoll_wait() The application then enters a loop where it waits for events using epoll_wait, For example,

ready_fds = epoll_wait(epoll_fd, events, MAX_EVENTS, -1);
  • 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,

len = recvfrom(client_socket, buffer, sizeof(buffer), 0, NULL, NULL);
  • sendto is used to send the encoded message to the specified server address and port using a socket. For example,

ret = sendto(client_socket, buffer, sizeof(struct icmphdr) + strlen(data), 0, (struct sockaddr*)&dest_addr, sizeof(dest_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>
#include <netinet/ip_icmp.h>
#include <netinet/ip.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/epoll.h>

#define BUFFER_SIZE 1024
#define MAX_EVENTS 2

struct sockaddr_in 
dest_addr;
int client_socket = -1;
int epoll_fd = -1;

static void sigint_handler(int signo)
{
  (void)close(client_socket);
  sleep(2);
  (void)printf("Caught sigINT!\n");
  exit(EXIT_SUCCESS);
}

void register_signal_handler(
int signum,
void (*handler)(int))
{
  if (signal(signum, handler) ==
  SIG_ERR) {
     printf("Cannot handle signal\n");
     exit(EXIT_FAILURE);
  }
}

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 send_icmp_message(
int client_socket, 
const char *data) 
{
  int ret;
  char buffer[BUFFER_SIZE];
  struct icmphdr *icmp_header;

  snprintf(buffer + 
  sizeof(struct icmphdr), sizeof(buffer) - 
  sizeof(struct icmphdr), "%s", data);

  icmp_header = (struct icmphdr *)buffer;
  icmp_header->type = ICMP_ECHO;
  icmp_header->code = 0;
  icmp_header->checksum = 0;
  icmp_header->un.echo.id = 0;
  icmp_header->un.echo.sequence = 0;

  ret = sendto(client_socket, 
  buffer, sizeof(struct icmphdr) + 
  strlen(data), 0,
  (struct sockaddr *)&dest_addr, 
  sizeof(dest_addr));
  
  if (ret < 0) {
    perror("sendto");
    (void)close(client_socket);
    exit(EXIT_FAILURE);
  }
}

void process_icmp_message(
char *buffer, 
ssize_t length)
{
  struct iphdr *ip_header;
  struct icmphdr *icmp_header; 
  char *original_data;  

  ip_header = (struct iphdr *)buffer;
  icmp_header = (struct icmphdr *)
  (buffer + sizeof(struct iphdr));

  printf("Received ICMP message:\n");
  printf("Source IP: %s\n", 
  inet_ntoa(*(struct in_addr *)&
  (ip_header->saddr)));
  printf("Type: %d\n", icmp_header->type);
  printf("Code: %d\n", icmp_header->code);

  original_data = buffer + 
  sizeof(struct iphdr) + 
  sizeof(struct icmphdr);
  printf("Original Data: %s\n", 
  original_data);
}

int main(int argc, char *argv[]) 
{
  int ret;
  int ready_fds;
  char buffer[BUFFER_SIZE];
  struct epoll_event
  events[MAX_EVENTS];
  struct epoll_event event;

  register_signal_handler(SIGINT,
  sigint_handler);

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

  memset(&dest_addr, 0, 
  sizeof(dest_addr));
  dest_addr.sin_family = AF_INET;
  validate_convert_addr(argv[1],
  &dest_addr);

  client_socket = socket(AF_INET, 
                  SOCK_RAW, 
                  IPPROTO_ICMP);
  
  if (client_socket < 0) {
    perror("Socket failed");
    exit(EXIT_FAILURE);
  }

  fcntl(client_socket, 
  F_SETFL, O_NONBLOCK);

  epoll_fd = epoll_create1(0);

  if (epoll_fd < 0) {
   perror("Epoll creation failed");
   (void)close(client_socket);
   return -1;
  }

  event.events = EPOLLIN | EPOLLET;
  event.data.fd = client_socket;
  ret = epoll_ctl(epoll_fd, EPOLL_CTL_ADD,
  client_socket, &event);

  if (ret  == -1) {
       perror("Epoll_ctl failed");
       (void)close(client_socket);
       return -2;
  }

  while (1) {
    send_icmp_message(client_socket, 
    "Hello from client!");

    sleep(2);

    ready_fds = epoll_wait(epoll_fd,
                events,
                MAX_EVENTS, -1);

    if (ready_fds < 0) {
      perror("Epoll wait failed");
      break;
    }

    if (events[0].data.fd ==
       client_socket) {
      ret = recvfrom(client_socket, 
      buffer, sizeof(buffer), 0, NULL, NULL);
    
      if (ret < 0) {
        perror("recv");
        break;
      } else {
         process_icmp_message(buffer, ret);
      }
    }
  }

  (void)close(client_socket);

  return 0;
}

$ gcc -o client client.c

$ sudo ./client 127.0.0.1

IP Address: 127.0.0.1
Received ICMP message:
Source IP: 127.0.0.1
Type: 8
Code: 0
Original Data: Hello from client!
Received ICMP message:
Source IP: 127.0.0.1
Type: 8
Code: 0
Original Data: Hello from server!
Received ICMP message:
Source IP: 127.0.0.1
Type: 8
Code: 0
Original Data: Hello from client!
Received ICMP message:
Source IP: 127.0.0.1
Type: 8
Code: 0
Original Data: Hello from server!
Received ICMP message:
Source IP: 127.0.0.1
Type: 8
Code: 0
Original Data: Hello from client!
^CCaught sigINT!

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_ICMP).

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

epoll

handles a set of file descriptors with different states, such as reading, writing, and exceptions, by using the struct epoll_event structure and the associated event flags..

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.