Packet Sniffer - Network Analyzer
Python-based packet sniffer using Scapy for live packet analysis and protocol inspection
Technologies Used
Packet Sniffer - Network Analyzer
Overview
Packet Sniffer is a Python-based network analysis tool built using Scapy that captures and analyzes network packets in real-time. The tool focuses on TCP/UDP/ICMP protocol decoding and provides real-time protocol inspection capabilities for network security analysis and troubleshooting.
Problem Statement
Network administrators and security professionals need tools to:
- Monitor Network Traffic: Understand what data flows through their networks
- Detect Anomalies: Identify suspicious or malicious network activity
- Troubleshoot Issues: Diagnose network connectivity and performance problems
- Learn Protocols: Understand how network protocols work at a low level
While tools like Wireshark exist, building a custom packet sniffer provides:
- Deeper understanding of network protocols
- Customizable analysis capabilities
- Lightweight, scriptable solution
- Educational value for cybersecurity learning
Solution
Packet Sniffer provides a Python-based solution with:
- Real-Time Capture: Live packet capture from network interfaces
- Protocol Decoding: Detailed analysis of TCP, UDP, and ICMP packets
- Filtering Capabilities: Focus on specific protocols or addresses
- Packet Statistics: Real-time statistics and summaries
- Export Functionality: Save captured packets for later analysis
Key Features
1. Live Packet Capture
- Capture packets from any network interface
- Support for promiscuous mode
- Real-time packet processing
- Minimal performance overhead
2. Protocol Analysis
- TCP: Sequence numbers, flags, window size, options
- UDP: Source/destination ports, payload length
- ICMP: Type, code, echo requests/replies
- IP: Source/destination addresses, TTL, fragmentation
- Ethernet: MAC addresses, frame types
3. Packet Filtering
- Filter by protocol (TCP/UDP/ICMP)
- Filter by IP address (source/destination)
- Filter by port number
- Custom BPF (Berkeley Packet Filter) expressions
4. Data Visualization
- Real-time packet count display
- Protocol distribution charts
- Top talkers identification
- Connection tracking
5. Export & Logging
- Save packets to PCAP format
- Export to CSV for analysis
- Detailed logging of suspicious activity
- Integration with other security tools
Technical Implementation
Architecture
Network Interface → Scapy Capture → Protocol Parser → Analysis Engine
↓
Display/Export
Technologies Used
- Language: Python 3.x
- Packet Capture: Scapy library
- Network Protocols: TCP/IP stack
- Data Processing: NumPy, Pandas
- Visualization: Matplotlib (optional)
Core Implementation
Packet Capture
from scapy.all import sniff, IP, TCP, UDP, ICMP
def packet_callback(packet):
"""Process each captured packet"""
if IP in packet:
ip_src = packet[IP].src
ip_dst = packet[IP].dst
protocol = packet[IP].proto
print(f"[+] {ip_src} -> {ip_dst} | Protocol: {protocol}")
# Analyze specific protocols
if TCP in packet:
analyze_tcp(packet)
elif UDP in packet:
analyze_udp(packet)
elif ICMP in packet:
analyze_icmp(packet)
def start_sniffing(interface="eth0", count=0):
"""Start packet capture"""
print(f"[*] Starting packet capture on {interface}")
sniff(iface=interface, prn=packet_callback, count=count, store=False)
TCP Analysis
def analyze_tcp(packet):
"""Analyze TCP packet details"""
tcp_layer = packet[TCP]
src_port = tcp_layer.sport
dst_port = tcp_layer.dport
seq_num = tcp_layer.seq
ack_num = tcp_layer.ack
flags = tcp_layer.flags
print(f" [TCP] {src_port} -> {dst_port}")
print(f" Seq: {seq_num}, Ack: {ack_num}")
print(f" Flags: {flags}")
# Detect SYN scan
if flags == "S":
print(" [!] Possible SYN scan detected")
# Detect suspicious ports
if dst_port in [22, 23, 3389]:
print(f" [!] Connection to sensitive port {dst_port}")
UDP Analysis
def analyze_udp(packet):
"""Analyze UDP packet details"""
udp_layer = packet[UDP]
src_port = udp_layer.sport
dst_port = udp_layer.dport
length = udp_layer.len
print(f" [UDP] {src_port} -> {dst_port}")
print(f" Length: {length} bytes")
# Detect DNS queries
if dst_port == 53:
print(" [*] DNS query detected")
# Detect potential DNS tunneling
if dst_port == 53 and length > 512:
print(" [!] Possible DNS tunneling (large query)")
ICMP Analysis
def analyze_icmp(packet):
"""Analyze ICMP packet details"""
icmp_layer = packet[ICMP]
icmp_type = icmp_layer.type
icmp_code = icmp_layer.code
print(f" [ICMP] Type: {icmp_type}, Code: {icmp_code}")
# Identify ICMP types
if icmp_type == 8:
print(" [*] Echo Request (Ping)")
elif icmp_type == 0:
print(" [*] Echo Reply (Pong)")
elif icmp_type == 3:
print(" [!] Destination Unreachable")
Packet Statistics
class PacketStats:
def __init__(self):
self.total_packets = 0
self.tcp_count = 0
self.udp_count = 0
self.icmp_count = 0
self.connections = {}
def update(self, packet):
"""Update statistics with new packet"""
self.total_packets += 1
if TCP in packet:
self.tcp_count += 1
elif UDP in packet:
self.udp_count += 1
elif ICMP in packet:
self.icmp_count += 1
# Track connections
if IP in packet:
conn = f"{packet[IP].src}:{packet[IP].dst}"
self.connections[conn] = self.connections.get(conn, 0) + 1
def display(self):
"""Display statistics"""
print("\n=== Packet Statistics ===")
print(f"Total Packets: {self.total_packets}")
print(f"TCP: {self.tcp_count}")
print(f"UDP: {self.udp_count}")
print(f"ICMP: {self.icmp_count}")
print("\nTop Connections:")
for conn, count in sorted(self.connections.items(),
key=lambda x: x[1], reverse=True)[:5]:
print(f" {conn}: {count} packets")
Key Components
1. Capture Engine
- Interface selection
- Promiscuous mode configuration
- Packet buffering
- Performance optimization
2. Protocol Parser
- Layer extraction (Ethernet, IP, TCP/UDP/ICMP)
- Header field parsing
- Payload extraction
- Checksum verification
3. Analysis Module
- Pattern detection
- Anomaly identification
- Statistical analysis
- Threat detection
4. Output Handler
- Console display
- File export (PCAP, CSV)
- Real-time logging
- Alert generation
My Contribution
As the sole developer of this ongoing project, I am responsible for:
- Architecture Design: Designed the modular packet analysis system
- Core Development: Implemented packet capture and protocol parsing
- Security Features: Added threat detection capabilities
- Testing: Conducted extensive testing on various networks
- Documentation: Creating comprehensive usage guides
Security Applications
1. Network Monitoring
- Monitor all traffic on a network segment
- Identify unauthorized devices
- Track bandwidth usage
2. Intrusion Detection
- Detect port scans
- Identify suspicious patterns
- Alert on known attack signatures
3. Protocol Analysis
- Understand protocol behavior
- Identify protocol violations
- Debug network applications
4. Forensics
- Capture evidence of network activity
- Reconstruct network sessions
- Timeline analysis
Challenges & Solutions
Challenge 1: Performance
Problem: Processing high-volume traffic without packet loss
Solution: Implemented efficient packet filtering and multi-threading
Challenge 2: Permissions
Problem: Packet capture requires root/admin privileges
Solution: Documented proper setup and created helper scripts for privilege management
Challenge 3: Protocol Complexity
Problem: Handling various protocol variations and edge cases
Solution: Leveraged Scapy's robust protocol parsing with custom validation
Results & Impact
- ✅ Successfully captures and analyzes packets in real-time
- ✅ Accurate protocol decoding for TCP/UDP/ICMP
- ✅ Minimal performance overhead (< 5% CPU usage)
- ✅ Educational tool for learning network protocols
- ✅ Useful for network troubleshooting and security analysis
Use Cases
1. Learning Tool
- Understand how protocols work
- Visualize network communication
- Practice network analysis skills
2. Security Testing
- Detect network vulnerabilities
- Identify insecure protocols
- Monitor for suspicious activity
3. Network Troubleshooting
- Diagnose connectivity issues
- Identify packet loss
- Analyze latency problems
4. Development & Testing
- Debug network applications
- Verify protocol implementations
- Test network configurations
Future Enhancements
- GUI interface for easier use
- Advanced filtering with regex
- Machine learning for anomaly detection
- Integration with IDS/IPS systems
- Support for encrypted traffic analysis
- Real-time visualization dashboard
- Mobile app for remote monitoring
- Cloud-based packet analysis
Project Timeline
Duration: October 2025 - Present (Ongoing)
- Month 1: Core packet capture implementation
- Month 2: Protocol parsing and analysis
- Month 3: Security features and threat detection
- Ongoing: Testing, optimization, and new features
Usage Example
# Basic packet capture
python packet_sniffer.py -i eth0
# Capture only TCP packets
python packet_sniffer.py -i eth0 -p tcp
# Filter by IP address
python packet_sniffer.py -i eth0 --src 192.168.1.100
# Save to PCAP file
python packet_sniffer.py -i eth0 -o capture.pcap
# Capture specific number of packets
python packet_sniffer.py -i eth0 -c 1000
Lessons Learned
- Low-Level Networking: Deep understanding of TCP/IP stack
- Performance Optimization: Efficient packet processing is crucial
- Security Awareness: Network traffic reveals a lot about systems
- Tool Development: Building tools enhances understanding
Conclusion
Packet Sniffer is an ongoing project that demonstrates practical network security analysis capabilities. It serves as both a learning tool and a functional network analyzer, providing insights into network traffic and potential security issues.
Project Status: In Development 🚧
GitHub: View Repository
Tech Stack: Python, Scapy, Network Protocols