Develop a Packet Capturing Application Using Raw Sockets

 

Develop a Packet Capturing Application Using Raw Sockets


Aim

To develop a packet capturing application using raw sockets in Linux that captures network packets and displays Ethernet, IP, TCP, UDP, and ICMP header information.


Objectives

After completing this experiment, students will be able to:

  1. Understand raw socket programming in Linux.
  2. Learn packet capturing techniques.
  3. Analyze Ethernet frame structure.
  4. Decode IPv4 packet headers.
  5. Extract source and destination MAC addresses.
  6. Extract source and destination IP addresses.
  7. Identify transport layer protocols (TCP, UDP, ICMP).
  8. Display TCP and UDP port numbers.
  9. Understand packet sniffing techniques.
  10. Develop basic network monitoring applications.

Prerequisites

Students should be familiar with:

  • Linux commands
  • Socket Programming
  • IP Addressing
  • TCP/IP Protocol Suite
  • C Programming

Theory

Introduction

Whenever data is transmitted over a network, it is divided into packets. Every packet contains:

  • Source address
  • Destination address
  • Protocol information
  • User data (payload)

Before reaching the destination, packets pass through several networking devices such as routers and switches.

A packet capturing application (also known as a packet sniffer) intercepts these packets and displays their contents for analysis.

Packet sniffers are widely used for:

  • Network troubleshooting
  • Security monitoring
  • Performance analysis
  • Intrusion detection
  • Protocol analysis

Popular packet analyzers include Wireshark, tcpdump, and Microsoft Network Monitor.


Raw Sockets

Normally, applications use TCP or UDP sockets.

These sockets provide processed data to applications.

A Raw Socket allows an application to receive packets before they are processed by the operating system's protocol stack.

This enables direct access to network packets and their headers.

Raw sockets can:

  • Capture all incoming packets
  • Capture outgoing packets
  • Examine packet headers
  • Build custom packets
  • Develop network monitoring tools

Since raw sockets have access to low-level network traffic, they require administrator (root) privileges.


Why Raw Sockets?

Raw sockets are used in applications such as:

  • Wireshark
  • tcpdump
  • Network Intrusion Detection Systems (IDS)
  • Firewalls
  • Network Monitoring Tools
  • Packet Analyzers
  • Traffic Analyzers

Socket Types

Socket TypeDescription
SOCK_STREAM    TCP communication
SOCK_DGRAM    UDP communication
SOCK_RAW    Direct packet access

Network Packet Structure

A packet captured from the network generally has the following format:

+---------------------------------------------------------+
|                 Ethernet Header (14 Bytes)              |
+---------------------------------------------------------+
|                    IP Header (20 Bytes)                 |
+---------------------------------------------------------+
|                 TCP / UDP / ICMP Header                 |
+---------------------------------------------------------+
|                     User Data (Payload)                 |
+---------------------------------------------------------+

Ethernet Frame

Every Ethernet frame contains:

FieldSize
Destination MAC    6 Bytes
Source MAC    6 Bytes
Protocol Type    2 Bytes
Data    Variable
----------------------------------------------------------
| Destination | Source | Type |        Data              |
| MAC Address | MAC    |      |                          |
----------------------------------------------------------

IPv4 Header

An IPv4 packet consists of:

FieldSize
Version4 bits
Header Length4 bits
Type of Service8 bits
Total Length16 bits
Identification16 bits
Flags3 bits
Fragment Offset13 bits
Time To Live (TTL)8 bits
Protocol8 bits
Header Checksum16 bits
Source IP32 bits
Destination IP32 bits

Protocol Numbers

Protocol    Number
ICMP    1
TCP    6
UDP    17

TCP Header

Important TCP fields include:

  • Source Port
  • Destination Port
  • Sequence Number
  • Acknowledgement Number
  • Header Length
  • Flags
  • Window Size
  • Checksum

UDP Header

A UDP header contains:

  • Source Port
  • Destination Port
  • Length
  • Checksum

ICMP Header

The ICMP header includes:

  • Type
  • Code
  • Checksum

Examples of ICMP messages include:

  • Echo Request (Ping)
  • Echo Reply
  • Destination Unreachable
  • Time Exceeded

Working Principle

The packet capturing application performs the following operations:

  1. Creates a raw socket using AF_PACKET.
  2. Listens for all incoming and outgoing Ethernet frames.
  3. Receives packets continuously using recvfrom().
  4. Extracts the Ethernet header.
  5. Determines whether the payload is an IPv4 packet.
  6. Extracts the IP header.
  7. Determines the transport layer protocol.
  8. Displays relevant header information.
  9. Continues capturing packets until the user terminates the program.

Architecture Diagram

                +---------------------------+
                |      Network Interface    |
                |   (Ethernet / Wi-Fi NIC)  |
                +-------------+-------------+
                              |
                    Incoming / Outgoing Packets
                              |
                              v
                 +-----------------------------+
                 |        Raw Socket           |
                 | (AF_PACKET, SOCK_RAW)       |
                 +-------------+---------------+
                               |
                        recvfrom()
                               |
                               v
                +------------------------------+
                | Packet Capture Application   |
                +------------------------------+
                | Extract Ethernet Header      |
                | Extract IP Header            |
                | Identify Protocol            |
                | Display Header Information   |
                +------------------------------+

Functions Used

FunctionPurpose
socket()    Creates a raw socket
recvfrom()    Receives packets
close()    Closes the socket
ntohs()    Converts network byte order to host byte order
inet_ntoa()    Converts IP address to dotted decimal notation
printf()    Displays packet information
memset()    Initializes memory
perror()    Displays error messages

Algorithm

Algorithm for Packet Capturing

  1. Start.
  2. Create a raw socket using socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL)).
  3. Check whether socket creation is successful.
  4. Allocate a buffer to store incoming packets.
  5. Continuously wait for packets using recvfrom().
  6. Extract the Ethernet header.
  7. Display:
    • Source MAC address
    • Destination MAC address
    • Ethernet Protocol
  8. If the packet is an IPv4 packet:
    • Extract the IP header.
    • Display:
      • Source IP address
      • Destination IP address
      • TTL
      • Protocol
  9. If the protocol is:
    • TCP → Display source and destination ports.
    • UDP → Display source and destination ports.
    • ICMP → Display ICMP type and code.
  10. Repeat Steps 5–9 until the program is terminated.
  11. Close the socket.
  12. Stop.

Program: packet_capture.c

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>

#include<arpa/inet.h>
#include<sys/socket.h>

#include<linux/if_packet.h>
#include<net/ethernet.h>

#include<netinet/ip.h>
#include<netinet/tcp.h>
#include<netinet/udp.h>
#include<netinet/ip_icmp.h>

#define BUFFER_SIZE 65536

void printMAC(unsigned char *mac)
{
    printf("%02X:%02X:%02X:%02X:%02X:%02X",
           mac[0],mac[1],mac[2],
           mac[3],mac[4],mac[5]);
}

int main()
{
    int sockfd;
    unsigned char *buffer;
    int data_size;

    struct sockaddr saddr;
    socklen_t saddr_len;

    buffer=(unsigned char *)malloc(BUFFER_SIZE);

    sockfd=socket(AF_PACKET,SOCK_RAW,htons(ETH_P_ALL));

    if(sockfd<0)
    {
        perror("Socket");
        return 1;
    }

    printf("\n==============================================\n");
    printf("        RAW SOCKET PACKET CAPTURE\n");
    printf("==============================================\n");
    printf("Press Ctrl+C to stop...\n\n");

    while(1)
    {
        saddr_len=sizeof(saddr);

        data_size=recvfrom(sockfd,
                           buffer,
                           BUFFER_SIZE,
                           0,
                           &saddr,
                           &saddr_len);

        if(data_size<0)
        {
            perror("recvfrom");
            break;
        }

        struct ethhdr *eth =
            (struct ethhdr *)buffer;

        printf("\n==============================================\n");
        printf("Packet Length : %d Bytes\n",data_size);

        printf("\nEthernet Header\n");
        printf("-----------------------------\n");

        printf("Destination MAC : ");
        printMAC(eth->h_dest);

        printf("\nSource MAC      : ");
        printMAC(eth->h_source);

        printf("\nProtocol        : 0x%04X\n",
                ntohs(eth->h_proto));

        if(ntohs(eth->h_proto)==ETH_P_IP)
        {
            struct iphdr *iph=
              (struct iphdr *)(buffer+
              sizeof(struct ethhdr));

            struct sockaddr_in src,dst;

            memset(&src,0,sizeof(src));
            memset(&dst,0,sizeof(dst));

            src.sin_addr.s_addr=iph->saddr;
            dst.sin_addr.s_addr=iph->daddr;

            printf("\nIP Header\n");
            printf("-----------------------------\n");

            printf("Source IP      : %s\n",
                    inet_ntoa(src.sin_addr));

            printf("Destination IP : %s\n",
                    inet_ntoa(dst.sin_addr));

            printf("TTL            : %d\n",
                    iph->ttl);

            printf("Protocol       : %d\n",
                    iph->protocol);

            if(iph->protocol==IPPROTO_TCP)
            {
                struct tcphdr *tcp=
                  (struct tcphdr*)
                  (buffer+
                  sizeof(struct ethhdr)+
                  iph->ihl*4);

                printf("\nTCP Header\n");
                printf("-----------------------------\n");

                printf("Source Port      : %u\n",
                       ntohs(tcp->source));

                printf("Destination Port : %u\n",
                       ntohs(tcp->dest));
            }

            else if(iph->protocol==IPPROTO_UDP)
            {
                struct udphdr *udp=
                  (struct udphdr*)
                  (buffer+
                  sizeof(struct ethhdr)+
                  iph->ihl*4);

                printf("\nUDP Header\n");
                printf("-----------------------------\n");

                printf("Source Port      : %u\n",
                        ntohs(udp->source));

                printf("Destination Port : %u\n",
                        ntohs(udp->dest));
            }

            else if(iph->protocol==IPPROTO_ICMP)
            {
                struct icmphdr *icmp=
                  (struct icmphdr*)
                  (buffer+
                  sizeof(struct ethhdr)+
                  iph->ihl*4);

                printf("\nICMP Header\n");
                printf("-----------------------------\n");

                printf("Type : %d\n",
                        icmp->type);

                printf("Code : %d\n",
                        icmp->code);
            }

            else
            {
                printf("\nOther Protocol\n");
            }
        }
    }

    close(sockfd);

    free(buffer);

    return 0;
}

Compilation

Compile the program using GCC.

gcc packet_capture.c -o packet_capture

If your Linux distribution requires additional warnings:

gcc packet_capture.c -Wall -o packet_capture

Execution

Raw sockets require administrator privileges.

sudo ./packet_capture

Generate network traffic by:

  • Opening a web browser
  • Running
ping google.com

or

ping 8.8.8.8

Every packet generated will be displayed.


Sample Output 1 (TCP Packet)

==============================================
RAW SOCKET PACKET CAPTURE
==============================================

Packet Length : 74 Bytes

Ethernet Header
-----------------------------
Destination MAC : D8:BB:C1:8A:7A:15
Source MAC      : 48:51:C5:27:11:90
Protocol        : 0x0800

IP Header
-----------------------------
Source IP      : 192.168.1.10
Destination IP : 142.250.183.14
TTL            : 64
Protocol       : 6

TCP Header
-----------------------------
Source Port      : 53215
Destination Port : 443

Sample Output 2 (UDP Packet)

Packet Length : 90 Bytes

Ethernet Header
-----------------------------
Destination MAC : D8:BB:C1:8A:7A:15
Source MAC      : 48:51:C5:27:11:90
Protocol        : 0x0800

IP Header
-----------------------------
Source IP      : 192.168.1.10
Destination IP : 8.8.8.8
TTL            : 128
Protocol       : 17

UDP Header
-----------------------------
Source Port      : 52018
Destination Port : 53

Sample Output 3 (ICMP Packet)

Packet Length : 98 Bytes

Ethernet Header
-----------------------------
Destination MAC : D8:BB:C1:8A:7A:15
Source MAC      : 48:51:C5:27:11:90
Protocol        : 0x0800

IP Header
-----------------------------
Source IP      : 192.168.1.10
Destination IP : 8.8.8.8
TTL            : 64
Protocol       : 1

ICMP Header
-----------------------------
Type : 8
Code : 0

Program Explanation

Step 1: Create a Raw Socket

sockfd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
  • AF_PACKET captures packets at the data-link layer.
  • SOCK_RAW provides direct access to packet data.
  • ETH_P_ALL captures all Ethernet protocols.

Step 2: Allocate a Buffer

buffer = (unsigned char *)malloc(BUFFER_SIZE);

A 64 KB buffer is allocated to store each received packet.


Step 3: Receive Packets

recvfrom(...)

The program continuously waits for incoming packets from the network interface.


Step 4: Extract Ethernet Header

struct ethhdr *eth =
      (struct ethhdr *)buffer;

This obtains the Ethernet frame information.

Displayed fields:

  • Source MAC
  • Destination MAC
  • Protocol Type

Step 5: Extract IP Header

struct iphdr *iph =
(struct iphdr *)
(buffer + sizeof(struct ethhdr));

The IP header begins immediately after the 14-byte Ethernet header.

Displayed fields:

  • Source IP
  • Destination IP
  • TTL
  • Protocol

Step 6: Decode the Transport Layer

The program checks the protocol field.

If TCP

if(iph->protocol==IPPROTO_TCP)

Displays:

  • Source Port
  • Destination Port

If UDP

if(iph->protocol==IPPROTO_UDP)

Displays:

  • Source Port
  • Destination Port

If ICMP

if(iph->protocol==IPPROTO_ICMP)

Displays:

  • ICMP Type
  • ICMP Code

Step 7: Repeat

The program continues capturing packets until the user presses Ctrl + C.

Understanding the Packet Structure

Every packet captured by the raw socket consists of several protocol headers followed by the actual data (payload).

+------------------------------------------------------------+
| Ethernet Header (14 Bytes)                                 |
+------------------------------------------------------------+
| IPv4 Header (20–60 Bytes)                                  |
+------------------------------------------------------------+
| TCP / UDP / ICMP Header                                    |
+------------------------------------------------------------+
| Application Data (Payload)                                 |
+------------------------------------------------------------+

The program reads each header sequentially and extracts useful information.


Ethernet Header Explanation

The Ethernet header is the first 14 bytes of every Ethernet frame.

FieldSizeDescription
Destination MAC    6 Bytes        Receiver's MAC address
Source MAC    6 Bytes        Sender's MAC address
Protocol Type    2 Bytes        Indicates the next protocol (IPv4, ARP, IPv6, etc.)

Example

Destination MAC : D8:BB:C1:8A:7A:15
Source MAC      : 48:51:C5:27:11:90
Protocol        : 0x0800

Protocol values:

Hex Value    Protocol
0x0800        IPv4
0x0806    ARP
0x86DD    IPv6

IP Header Explanation

The IPv4 header provides logical addressing and routing information.

FieldDescription
Version        IP version (4 for IPv4)
Header Length    Size of the IP header
Total Length    Total packet size
TTL    Maximum number of router hops
Protocol    Next layer protocol
Source IP    Sender's IP address
Destination IP    Receiver's IP address

Example

Source IP      : 192.168.1.15
Destination IP : 142.250.183.14
TTL            : 64
Protocol       : 6

TCP Header Explanation

When the IP protocol field equals 6, the packet contains a TCP header.

Important fields:

FieldDescription
Source Port    Sender's port number
Destination Port    Receiver's port number
Sequence Number    Order of transmitted bytes
Acknowledgement Number    Next expected byte
Flags    SYN, ACK, FIN, etc.
Window Size    Flow control

Example:

Source Port      : 53215
Destination Port : 443

Port 443 indicates HTTPS traffic.


UDP Header Explanation

When the protocol field equals 17, the packet contains a UDP header.

UDP has only four fields:

FieldDescription
Source Port    Sender port
Destination Port    Receiver port
Length    UDP datagram length
Checksum    Error detection

Example

Source Port      : 52345
Destination Port : 53

Port 53 indicates DNS traffic.


ICMP Header Explanation

ICMP packets are mainly used for diagnostics.

Common ICMP messages:

TypeMeaning
0    Echo Reply
3    Destination Unreachable
8    Echo Request
11    Time Exceeded

Example

Type : 8
Code : 0

This represents a Ping Request.


Common Port Numbers

PortService
20    FTP Data
21    FTP Control
22    SSH
23    Telnet
25    SMTP
53    DNS
67    DHCP Server
68    DHCP Client
80    HTTP
110    POP3
143    IMAP
443HTTPS

Applications

Raw socket programming and packet capture are widely used in:

  1. Network traffic monitoring
  2. Protocol analysis
  3. Intrusion Detection Systems (IDS)
  4. Firewall development
  5. Packet filtering
  6. Network troubleshooting
  7. Cybersecurity research
  8. Malware analysis
  9. Digital forensics
  10. Performance monitoring
  11. Quality of Service (QoS) analysis
  12. Network protocol debugging

Advantages

  1. Provides direct access to network packets.
  2. Enables detailed packet inspection.
  3. Useful for protocol analysis and learning.
  4. Supports network debugging and troubleshooting.
  5. Helps identify malicious traffic.
  6. Assists in performance monitoring.
  7. Can capture multiple protocols.
  8. Useful for developing network monitoring tools.
  9. Demonstrates low-level networking concepts.
  10. Suitable for educational and research purposes.

Limitations

  1. Requires administrator (root) privileges.
  2. Platform dependent (Linux-specific implementation using AF_PACKET).
  3. Captures large volumes of traffic, which can be difficult to analyze manually.
  4. High packet rates may overwhelm the application.
  5. Captured data may contain sensitive information and must be handled responsibly.
  6. The sample program only parses IPv4, TCP, UDP, and ICMP packets.
  7. Does not store captured packets in a file (e.g., PCAP format).
  8. Does not reassemble fragmented IP packets.
  9. Does not decode application-layer protocols such as HTTP or DNS.

Precautions

  1. Execute the program with sudo privileges.
  2. Ensure the network interface is active.
  3. Generate traffic (e.g., ping, web browsing) to observe captured packets.
  4. Do not modify or inject packets using this program.
  5. Use the program only on networks where you have authorization to monitor traffic.
  6. Terminate the program with Ctrl + C after the observation.


Result

A packet-capturing application was successfully developed using raw sockets in Linux. The program captured Ethernet frames directly from the network interface, decoded IPv4 packets, identified TCP, UDP, and ICMP protocols, and displayed relevant information such as MAC addresses, IP addresses, protocol numbers, TTL values, and transport-layer port numbers. The experiment demonstrated the fundamentals of low-level packet analysis and raw socket programming.

Comments

Popular posts from this blog

Networks Lab PCCSL507 Semester 5 KTU CS 2024 Scheme - Dr Binu V P

Study of whois Command

Study and Use of ifconfig Command