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:
- Understand raw socket programming in Linux.
- Learn packet capturing techniques.
- Analyze Ethernet frame structure.
- Decode IPv4 packet headers.
- Extract source and destination MAC addresses.
- Extract source and destination IP addresses.
- Identify transport layer protocols (TCP, UDP, ICMP).
- Display TCP and UDP port numbers.
- Understand packet sniffing techniques.
- 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 Type | Description |
|---|---|
| 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:
| Field | Size |
|---|---|
| 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:
| Field | Size |
|---|---|
| Version | 4 bits |
| Header Length | 4 bits |
| Type of Service | 8 bits |
| Total Length | 16 bits |
| Identification | 16 bits |
| Flags | 3 bits |
| Fragment Offset | 13 bits |
| Time To Live (TTL) | 8 bits |
| Protocol | 8 bits |
| Header Checksum | 16 bits |
| Source IP | 32 bits |
| Destination IP | 32 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:
-
Creates a raw socket using
AF_PACKET. - Listens for all incoming and outgoing Ethernet frames.
-
Receives packets continuously using
recvfrom(). - Extracts the Ethernet header.
- Determines whether the payload is an IPv4 packet.
- Extracts the IP header.
- Determines the transport layer protocol.
- Displays relevant header information.
- 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
| Function | Purpose |
|---|---|
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
- Start.
-
Create a raw socket using
socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL)). - Check whether socket creation is successful.
- Allocate a buffer to store incoming packets.
-
Continuously wait for packets using
recvfrom(). - Extract the Ethernet header.
-
Display:
- Source MAC address
- Destination MAC address
- Ethernet Protocol
-
If the packet is an IPv4 packet:
- Extract the IP header.
-
Display:
- Source IP address
- Destination IP address
- TTL
- Protocol
-
If the protocol is:
- TCP → Display source and destination ports.
- UDP → Display source and destination ports.
- ICMP → Display ICMP type and code.
- Repeat Steps 5–9 until the program is terminated.
- Close the socket.
- 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_PACKETcaptures packets at the data-link layer. -
SOCK_RAWprovides direct access to packet data. -
ETH_P_ALLcaptures 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.
| Field | Size | Description |
|---|---|---|
| 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.
| Field | Description |
|---|---|
| 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:
| Field | Description |
|---|---|
| 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:
| Field | Description |
|---|---|
| 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:
| Type | Meaning |
|---|---|
| 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
| Port | Service |
|---|---|
| 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 |
| 443 | HTTPS |
Applications
Raw socket programming and packet capture are widely used in:
- Network traffic monitoring
- Protocol analysis
- Intrusion Detection Systems (IDS)
- Firewall development
- Packet filtering
- Network troubleshooting
- Cybersecurity research
- Malware analysis
- Digital forensics
- Performance monitoring
- Quality of Service (QoS) analysis
- Network protocol debugging
Advantages
- Provides direct access to network packets.
- Enables detailed packet inspection.
- Useful for protocol analysis and learning.
- Supports network debugging and troubleshooting.
- Helps identify malicious traffic.
- Assists in performance monitoring.
- Can capture multiple protocols.
- Useful for developing network monitoring tools.
- Demonstrates low-level networking concepts.
- Suitable for educational and research purposes.
Limitations
- Requires administrator (root) privileges.
-
Platform dependent (Linux-specific implementation using
AF_PACKET). - Captures large volumes of traffic, which can be difficult to analyze manually.
- High packet rates may overwhelm the application.
- Captured data may contain sensitive information and must be handled responsibly.
- The sample program only parses IPv4, TCP, UDP, and ICMP packets.
- Does not store captured packets in a file (e.g., PCAP format).
- Does not reassemble fragmented IP packets.
- Does not decode application-layer protocols such as HTTP or DNS.
Precautions
-
Execute the program with
sudoprivileges. - Ensure the network interface is active.
-
Generate traffic (e.g.,
ping, web browsing) to observe captured packets. - Do not modify or inject packets using this program.
- Use the program only on networks where you have authorization to monitor traffic.
- 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
Post a Comment