E. Read RAW Socket in Unix Using C Programming

Read RAW Socket

/*PROGRAM FOR RAW SOCKET IN C*/

#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/ip.h>

int main() {
   int sockfd;

   char buff[8192] = "";
   struct iphdr *ip;
   sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
   while (read(sockfd, buff, 8192)) {
      ip = (struct iphdr *) buff;
      printf("\nSource: %s \n", inet_ntoa(ip->saddr));
      printf("Destnation: %s\n", inet_ntoa(ip->daddr));
   }
}

Sample Output

[root@localhost ~]# ./a.out

Source: 172.16.29.123 
Destnation: 172.16.29.60

Source: 172.16.29.123 
Destnation: 172.16.29.60

Source: 172.16.29.123 
Destnation: 172.16.29.60

Source: 172.16.29.123 
Destnation: 172.16.29.60

Source: 172.16.29.123 
Destnation: 172.16.29.60

Source: 172.16.29.123 
Destnation: 172.16.29.60

Source: 172.16.29.123 
Destnation: 172.16.29.60