Packet Sniffer
A simple packet sniffer written in C that captures TCP and DNS packets and saves them to a capture.pcap file.
Designed for educational purposes to demonstrate how raw sockets can be used to monitor network traffic and analyze packet structures.
Overview
The sniffer uses raw sockets to listen to all traffic on the network interface. It parses Ethernet, IP, TCP, and UDP headers in real-time to provide human-readable output while simultaneously logging the raw data for deeper analysis.
Key characteristics:
- Raw Socket Usage: Operates at the link layer to capture all frames.
- Protocol Parsing: Specifically identifies and extracts information from TCP and DNS (UDP) packets.
- PCAP Logging: Generates standard
capture.pcapfiles compatible with Wireshark andtcpdump. - Payload Inspection: Displays ASCII representation of packet payloads for quick debugging.
Build & Run
Prerequisites
- GCC compiler
- Root/Sudo privileges (required for raw sockets)
Compile
make
Run
sudo ./sniffer
To stop capturing, press Ctrl+C. The program will gracefully close the socket and the output file.
Features
| Feature | Description |
|---|---|
| 🕵️ Real-time Capture | Captures all packets on the network interface using ETH_P_ALL. |
| 📂 Wireshark Ready | Automatically writes a PCAP global header and individual packet headers for standard analysis tools. |
| 🔍 Protocol Filtering | Dedicated logic for TCP (ports, payload) and DNS (queries). |
| 🛡️ Graceful Shutdown | Handles SIGINT to ensure the PCAP file is properly closed and memory is freed. |
Output Examples
TCP Packet
TCP Packet: 192.168.1.15:443 -> 192.168.1.20:54321
Payload (24 bytes):
....G...S................
DNS Request
DNS Request: 192.168.1.15 -> 8.8.8.8
Query data: ...google.com.....
How it Works
- Initialization: Opens a raw socket
AF_PACKETwithETH_P_ALL. - PCAP Header: Writes the global PCAP header to the output file.
- Capture Loop:
- Receives raw frames from the socket.
- Prepends a PCAP packet header (timestamp, size).
- Writes the frame to disk.
- Decodes Ethernet, IP, and transport layer headers for terminal display.
- Cleanup: Closes the file and socket on exit.
Future Improvements
- Interface Selection: Allow choosing a specific network interface (e.g.,
eth0,wlan0). - Enhanced Filtering: Add BPF (Berkeley Packet Filter) support for more efficient kernel-level filtering.
- Protocol Support: Add support for ICMP, ARP, and HTTP parsing.
- Statistics: Display capture statistics (packets per second, bandwidth usage).
Disclaimer: Use this tool only on networks you own or have explicit permission to monitor. Unauthorized packet sniffing is illegal and unethical.