Network Traffic Analysis with tcpdump: Complete Guide

Introduction

tcpdump is the quintessential command-line packet analyzer for Unix-like systems, providing powerful capabilities for capturing, filtering, and analyzing network traffic in real-time. As one of the most essential network troubleshooting tools in a system administrator's toolkit, tcpdump enables deep inspection of network communications, helping diagnose connectivity issues, security incidents, performance problems, and protocol anomalies. Unlike graphical packet analyzers like Wireshark, tcpdump's command-line interface makes it ideal for remote server administration, automated monitoring scripts, and situations where GUI access is unavailable or impractical.

tcpdump operates by placing network interfaces into promiscuous mode, allowing capture of all packets on the network segment, not just those destined for the local system. Built on the libpcap library, it supports comprehensive filtering using Berkeley Packet Filter (BPF) syntax, enabling precise capture of specific traffic patterns while minimizing performance impact and storage requirements. Whether you're troubleshooting application behavior, investigating security breaches, validating firewall rules, or documenting network protocols, tcpdump provides the low-level packet visibility essential for understanding network behavior.

This comprehensive guide covers tcpdump from fundamental concepts to advanced analysis techniques, including capture filters, protocol dissection, file operations, performance optimization, security considerations, and practical troubleshooting scenarios. By mastering tcpdump, you'll gain unprecedented insight into network communications and develop essential skills for maintaining robust, secure infrastructure.

Understanding Packet Capture

How tcpdump Works

Packet capture process:

  1. Interface Selection - Choose network interface to monitor
  2. Promiscuous Mode - Interface captures all packets, not just those destined for host
  3. Kernel Filtering - BPF filters applied at kernel level for efficiency
  4. Packet Capture - libpcap captures packets matching filters
  5. Output/Storage - Display to terminal or save to file

When to Use tcpdump

Common use cases:

  • Troubleshooting connectivity - Identify dropped packets, routing issues
  • Security analysis - Investigate suspicious traffic, potential intrusions
  • Protocol debugging - Examine application-level protocol exchanges
  • Performance analysis - Identify latency sources, bandwidth hogs
  • Firewall validation - Verify rules allow/block expected traffic
  • Network documentation - Capture traffic patterns for analysis

Prerequisites

Before using tcpdump, ensure you have:

  • Root or sudo privileges (packet capture requires elevated permissions)
  • tcpdump installed on your system
  • Understanding of TCP/IP networking fundamentals
  • Knowledge of protocols you'll be analyzing
  • Sufficient disk space for packet captures (if saving to file)
  • Legal authorization to capture network traffic

Installation

Debian/Ubuntu:

sudo apt update
sudo apt install tcpdump -y

RHEL/CentOS/Rocky Linux:

sudo dnf install tcpdump -y

Verify installation:

tcpdump --version

Permissions

# Run as root
sudo tcpdump

# Or grant capabilities to specific user (careful with security implications)
sudo setcap cap_net_raw,cap_net_admin=eip /usr/bin/tcpdump

Basic tcpdump Usage

Listing Network Interfaces

# List available interfaces
tcpdump -D

# Example output:
# 1.eth0 [Up, Running]
# 2.lo [Up, Running, Loopback]
# 3.any (Pseudo-device that captures on all interfaces)

Basic Capture Commands

# Capture on first available interface
sudo tcpdump

# Capture on specific interface
sudo tcpdump -i eth0

# Capture on all interfaces
sudo tcpdump -i any

# Limit number of packets
sudo tcpdump -c 10

# Disable name resolution (faster)
sudo tcpdump -n

# Disable port name resolution
sudo tcpdump -nn

# More verbose output
sudo tcpdump -v
sudo tcpdump -vv
sudo tcpdump -vvv

Understanding Output Format

$ sudo tcpdump -i eth0 -c 1

17:45:23.123456 IP 192.168.1.100.54321 > 8.8.8.8.53: UDP, length 29

Output breakdown:

  • 17:45:23.123456 - Timestamp
  • IP - Protocol
  • 192.168.1.100.54321 - Source IP and port
  • > - Direction
  • 8.8.8.8.53 - Destination IP and port
  • UDP - Transport protocol
  • length 29 - Packet length

Capture Filters

Host Filters

# Capture traffic from/to specific host
sudo tcpdump host 192.168.1.100

# Only traffic from host
sudo tcpdump src host 192.168.1.100

# Only traffic to host
sudo tcpdump dst host 192.168.1.100

# Traffic between two hosts
sudo tcpdump host 192.168.1.100 and host 192.168.1.200

# Exclude specific host
sudo tcpdump not host 192.168.1.100

Network Filters

# Capture traffic for entire subnet
sudo tcpdump net 192.168.1.0/24

# Source network
sudo tcpdump src net 192.168.1.0/24

# Destination network
sudo tcpdump dst net 10.0.0.0/8

Port Filters

# Specific port
sudo tcpdump port 80

# Source port
sudo tcpdump src port 1234

# Destination port
sudo tcpdump dst port 443

# Port range
sudo tcpdump portrange 1000-2000

# Multiple ports
sudo tcpdump port 80 or port 443
sudo tcpdump 'port 80 or port 443'

Protocol Filters

# TCP traffic only
sudo tcpdump tcp

# UDP traffic only
sudo tcpdump udp

# ICMP traffic (ping)
sudo tcpdump icmp

# IPv6 traffic
sudo tcpdump ip6

# ARP packets
sudo tcpdump arp

Combining Filters

# AND operator
sudo tcpdump host 192.168.1.100 and port 80

# OR operator
sudo tcpdump host 192.168.1.100 or host 192.168.1.200

# NOT operator
sudo tcpdump not port 22

# Complex combinations
sudo tcpdump 'host 192.168.1.100 and (port 80 or port 443)'

# Parentheses for grouping
sudo tcpdump '(src host 192.168.1.100 or src host 192.168.1.200) and tcp port 80'

Advanced Filtering

TCP Flags Filtering

# SYN packets (connection establishment)
sudo tcpdump 'tcp[tcpflags] & tcp-syn != 0'

# SYN-ACK packets
sudo tcpdump 'tcp[tcpflags] & (tcp-syn|tcp-ack) == (tcp-syn|tcp-ack)'

# RST packets (connection reset)
sudo tcpdump 'tcp[tcpflags] & tcp-rst != 0'

# FIN packets (connection termination)
sudo tcpdump 'tcp[tcpflags] & tcp-fin != 0'

# PSH packets (push data)
sudo tcpdump 'tcp[tcpflags] & tcp-push != 0'

Packet Size Filtering

# Packets larger than 1000 bytes
sudo tcpdump 'greater 1000'

# Packets smaller than 100 bytes
sudo tcpdump 'less 100'

# Packets exactly 64 bytes
sudo tcpdump 'len == 64'

Content Matching

# HTTP GET requests
sudo tcpdump -A 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)' | grep -i "GET"

# Search for specific string in payload
sudo tcpdump -A -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)' | grep -i "password"

# Simpler: capture HTTP traffic containing "User-Agent"
sudo tcpdump -A 'tcp port 80' | grep -i "User-Agent"

MAC Address Filtering

# Specific MAC address
sudo tcpdump ether host 00:11:22:33:44:55

# Source MAC
sudo tcpdump ether src 00:11:22:33:44:55

# Destination MAC
sudo tcpdump ether dst 00:11:22:33:44:55

VLAN Filtering

# Capture VLAN traffic
sudo tcpdump 'vlan'

# Specific VLAN ID
sudo tcpdump 'vlan 100'

# Traffic on VLAN to specific host
sudo tcpdump 'vlan and host 192.168.1.100'

Output Options

Display Options

# Show packet data in hex and ASCII
sudo tcpdump -X

# Show packet data in ASCII only
sudo tcpdump -A

# Show packet data in hex only
sudo tcpdump -x

# Include link-level headers
sudo tcpdump -e

# Show absolute sequence numbers
sudo tcpdump -S

# Capture full packet (default truncates at 262144 bytes)
sudo tcpdump -s 0

# Set specific snapshot length
sudo tcpdump -s 1500

Timestamp Options

# Absolute timestamp
sudo tcpdump -tttt

# Unix timestamp
sudo tcpdump -tt

# Time since previous packet
sudo tcpdump -ttt

# Microsecond precision
sudo tcpdump -tttt

Quiet Mode

# Minimal output
sudo tcpdump -q

# Very quiet (just packet count)
sudo tcpdump -qq

Saving and Reading Captures

Saving to File

# Save to pcap file
sudo tcpdump -w capture.pcap

# Save with packet count limit
sudo tcpdump -c 1000 -w capture.pcap

# Save to file with specific interface
sudo tcpdump -i eth0 -w eth0-capture.pcap

# Rotate capture files by size (100MB per file)
sudo tcpdump -W 5 -C 100 -w capture.pcap
# Creates: capture.pcap0, capture.pcap1, capture.pcap2, etc.

# Rotate by time (new file every hour)
sudo tcpdump -G 3600 -w capture-%Y%m%d-%H%M%S.pcap

Reading from File

# Read pcap file
sudo tcpdump -r capture.pcap

# Read with filters
sudo tcpdump -r capture.pcap 'port 80'

# Read with specific output format
sudo tcpdump -r capture.pcap -nn -A

# Count packets in file
tcpdump -r capture.pcap | wc -l

Combining Capture and Display

# Capture to file and display simultaneously
sudo tcpdump -i eth0 -w capture.pcap -v

# Buffer to file while reading from another
sudo tcpdump -r old-capture.pcap -w new-capture.pcap 'host 192.168.1.100'

Practical Analysis Scenarios

Scenario 1: Troubleshooting HTTP Connectivity

# Capture HTTP traffic to/from web server
sudo tcpdump -i eth0 -nn -A 'host 192.168.1.100 and port 80'

# Look for HTTP requests
sudo tcpdump -i eth0 -nn -A 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'

# Check for specific HTTP method
sudo tcpdump -i eth0 -A 'tcp port 80' | grep -E 'GET|POST|PUT|DELETE'

# Capture response codes
sudo tcpdump -i eth0 -A 'tcp port 80' | grep -E 'HTTP/1.[01] [0-9]{3}'

Scenario 2: Debugging DNS Issues

# Capture DNS queries and responses
sudo tcpdump -i eth0 -nn 'port 53'

# DNS queries only
sudo tcpdump -i eth0 -nn 'udp port 53'

# Specific domain queries
sudo tcpdump -i eth0 -nn 'port 53 and host 8.8.8.8'

# Verbose DNS output
sudo tcpdump -i eth0 -vv 'port 53'

Scenario 3: Analyzing SSH Connections

# Capture SSH traffic
sudo tcpdump -i eth0 'port 22'

# See SSH connection attempts
sudo tcpdump -i eth0 -nn 'tcp port 22 and tcp[tcpflags] & tcp-syn != 0'

# Failed SSH connections (RST packets)
sudo tcpdump -i eth0 -nn 'tcp port 22 and tcp[tcpflags] & tcp-rst != 0'

# Specific SSH session
sudo tcpdump -i eth0 'host 192.168.1.50 and port 22' -w ssh-session.pcap

Scenario 4: Detecting Port Scans

# SYN scan detection (SYN packets without established connections)
sudo tcpdump -i eth0 -nn 'tcp[tcpflags] & tcp-syn != 0 and tcp[tcpflags] & tcp-ack == 0'

# NULL scan (no flags set)
sudo tcpdump -i eth0 -nn 'tcp[tcpflags] == 0'

# XMAS scan (FIN, PSH, URG flags set)
sudo tcpdump -i eth0 -nn 'tcp[tcpflags] & (tcp-fin|tcp-push|tcp-urg) == (tcp-fin|tcp-push|tcp-urg)'

# Monitor multiple ports
sudo tcpdump -i eth0 -nn 'tcp[tcpflags] & tcp-syn != 0 and tcp[tcpflags] & tcp-ack == 0' | awk '{print $3}' | cut -d'.' -f1-4 | sort | uniq -c

Scenario 5: Monitoring Database Traffic

# MySQL traffic
sudo tcpdump -i eth0 'port 3306'

# PostgreSQL traffic
sudo tcpdump -i eth0 'port 5432'

# MongoDB traffic
sudo tcpdump -i eth0 'port 27017'

# Capture database queries (MySQL example)
sudo tcpdump -i eth0 -s 0 -A 'port 3306' | grep -i "select\|insert\|update\|delete"

Scenario 6: SSL/TLS Analysis

# Capture HTTPS traffic
sudo tcpdump -i eth0 'port 443'

# SSL handshake packets
sudo tcpdump -i eth0 -nn 'tcp port 443 and (tcp[((tcp[12:1] & 0xf0) >> 2):1] = 0x16)'

# Specific SSL/TLS host
sudo tcpdump -i eth0 -nn 'host 192.168.1.100 and port 443' -w ssl-session.pcap

Scenario 7: Bandwidth Analysis

# Top bandwidth consumers by IP
sudo tcpdump -i eth0 -nn -q | awk '{print $3}' | cut -d'.' -f1-4 | sort | uniq -c | sort -rn | head

# Traffic by protocol
sudo tcpdump -i eth0 -nn | awk '{print $2}' | sort | uniq -c

# Capture for bandwidth calculation
sudo tcpdump -i eth0 -w bandwidth.pcap -G 60 -W 1
# Analyze with tcpdump or wireshark

Protocol-Specific Captures

ICMP (Ping)

# All ICMP traffic
sudo tcpdump -i eth0 icmp

# Echo requests (ping)
sudo tcpdump -i eth0 'icmp[icmptype] == icmp-echo'

# Echo replies
sudo tcpdump -i eth0 'icmp[icmptype] == icmp-echoreply'

# Destination unreachable
sudo tcpdump -i eth0 'icmp[icmptype] == icmp-unreach'

ARP

# All ARP traffic
sudo tcpdump -i eth0 arp

# ARP requests
sudo tcpdump -i eth0 'arp and arp[6:2] == 1'

# ARP replies
sudo tcpdump -i eth0 'arp and arp[6:2] == 2'

# Detect ARP spoofing
sudo tcpdump -i eth0 -e -n arp | grep -i "who-has"

DHCP

# DHCP traffic
sudo tcpdump -i eth0 -nn 'port 67 or port 68'

# DHCP discover
sudo tcpdump -i eth0 -vv 'udp port 67 and udp[8:1] == 0x01'

# DHCP offer
sudo tcpdump -i eth0 -vv 'udp port 68 and udp[8:1] == 0x02'

SMTP

# SMTP traffic
sudo tcpdump -i eth0 'port 25'

# SMTP commands
sudo tcpdump -i eth0 -A 'port 25' | grep -E 'HELO|MAIL FROM|RCPT TO|DATA'

# SMTP with authentication
sudo tcpdump -i eth0 'port 587'

Performance Considerations

Efficient Filtering

# Filter at kernel level (faster)
sudo tcpdump -i eth0 'port 80'

# Avoid filtering in userspace
# Bad: sudo tcpdump -i eth0 | grep "port 80"
# Good: sudo tcpdump -i eth0 'port 80'

Limiting Capture Size

# Capture packet headers only (faster, smaller files)
sudo tcpdump -s 96 -i eth0

# Limit number of packets
sudo tcpdump -c 10000 -i eth0

# Buffer size adjustment
sudo tcpdump -B 4096 -i eth0

CPU Usage Optimization

# Reduce verbosity
sudo tcpdump -i eth0 -q 'port 80'

# Disable name resolution
sudo tcpdump -i eth0 -nn 'port 80'

# Use specific filters to reduce packet processing
sudo tcpdump -i eth0 'host 192.168.1.100 and port 80'

Security Considerations

Capturing Sensitive Data

Be aware that tcpdump can capture:

  • Passwords transmitted in cleartext
  • Session cookies
  • Personal information
  • Proprietary data

Best practices:

# Limit capture to headers only
sudo tcpdump -s 96

# Avoid capturing on production systems when possible
# Use in isolated troubleshooting environments

# Secure captured files
chmod 600 capture.pcap

# Delete captures after analysis
shred -u capture.pcap

Legal and Ethical Considerations

  • Authorization required - Only capture traffic you're authorized to monitor
  • Privacy laws - Comply with GDPR, HIPAA, and other regulations
  • Corporate policy - Follow organizational security policies
  • Minimal capture - Capture only necessary traffic
  • Secure storage - Protect captured files from unauthorized access

Encrypted Traffic

# HTTPS traffic is encrypted (can't see content)
sudo tcpdump -i eth0 'port 443' -A
# Output shows encrypted data, not readable content

# See metadata only (IPs, ports, timestamps)
sudo tcpdump -i eth0 -nn 'port 443'

Automation and Scripting

Automated Capture Script

#!/bin/bash
# capture-monitor.sh

INTERFACE="eth0"
FILTER="port 80 or port 443"
DURATION=3600  # 1 hour
OUTPUT_DIR="/var/captures"
TIMESTAMP=$(date +%Y%m%d-%H%M%S)

mkdir -p $OUTPUT_DIR

# Start capture
sudo tcpdump -i $INTERFACE -nn -s 0 \
    -G $DURATION -W 1 \
    -w $OUTPUT_DIR/capture-$TIMESTAMP.pcap \
    "$FILTER"

echo "Capture saved to $OUTPUT_DIR/capture-$TIMESTAMP.pcap"

Monitoring Script with Alerts

#!/bin/bash
# monitor-suspicious.sh

INTERFACE="eth0"
ALERT_EMAIL="[email protected]"

# Monitor for port scans
sudo tcpdump -i $INTERFACE -nn -l \
    'tcp[tcpflags] & tcp-syn != 0 and tcp[tcpflags] & tcp-ack == 0' | \
while read line; do
    SRC_IP=$(echo $line | awk '{print $3}' | cut -d'.' -f1-4)

    # Count SYN packets from same source
    COUNT=$(timeout 10 sudo tcpdump -i $INTERFACE -nn \
        "src host $SRC_IP and tcp[tcpflags] & tcp-syn != 0" 2>/dev/null | wc -l)

    if [ $COUNT -gt 20 ]; then
        echo "Possible port scan from $SRC_IP" | \
            mail -s "Security Alert: Port Scan Detected" $ALERT_EMAIL
    fi
done

Periodic Capture with Rotation

#!/bin/bash
# periodic-capture.sh

INTERFACE="eth0"
ROTATION_SIZE=100  # MB
MAX_FILES=10
OUTPUT_PREFIX="/var/captures/periodic"

sudo tcpdump -i $INTERFACE -nn -s 0 \
    -C $ROTATION_SIZE -W $MAX_FILES \
    -w $OUTPUT_PREFIX.pcap

Troubleshooting tcpdump

Common Issues

Permission denied:

# Run with sudo
sudo tcpdump -i eth0

# Or set capabilities
sudo setcap cap_net_raw,cap_net_admin=eip /usr/bin/tcpdump

No suitable device found:

# List available interfaces
tcpdump -D

# Check interface exists
ip link show

# Try any interface
sudo tcpdump -i any

Capture shows no packets:

# Verify interface is up
ip link show eth0

# Check filters are not too restrictive
sudo tcpdump -i eth0  # No filters

# Verify traffic exists
ping -c 1 google.com &
sudo tcpdump -i eth0 'icmp'

High CPU usage:

# Use more specific filters
sudo tcpdump -i eth0 'host 192.168.1.100'

# Reduce verbosity
sudo tcpdump -i eth0 -q

# Disable name resolution
sudo tcpdump -i eth0 -nn

Best Practices

1. Use Specific Filters

# Narrow capture to relevant traffic
sudo tcpdump -i eth0 'host 192.168.1.100 and port 80'

2. Disable Name Resolution

# Faster performance, clearer output
sudo tcpdump -i eth0 -nn

3. Limit Capture Duration

# Prevent excessive disk usage
sudo tcpdump -i eth0 -c 10000 -w capture.pcap
sudo tcpdump -i eth0 -G 300 -W 1 -w capture.pcap

4. Secure Capture Files

# Restrict permissions
chmod 600 *.pcap

# Encrypt sensitive captures
gpg -c sensitive-capture.pcap

# Delete after analysis
shred -u capture.pcap

5. Document Captures

# Include metadata
echo "Capture Date: $(date)" > capture-metadata.txt
echo "Interface: eth0" >> capture-metadata.txt
echo "Filter: host 192.168.1.100" >> capture-metadata.txt
echo "Purpose: Troubleshooting web server" >> capture-metadata.txt

6. Combine with Other Tools

# Export to Wireshark for GUI analysis
sudo tcpdump -i eth0 -w capture.pcap
wireshark capture.pcap

# Pipe to text processing
sudo tcpdump -i eth0 -nn -l | awk '{print $3}' | cut -d'.' -f1-4 | sort | uniq -c

Conclusion

tcpdump is an indispensable tool for network troubleshooting, security analysis, and protocol debugging on Linux systems. Its powerful filtering capabilities, efficiency, and ubiquity across Unix-like platforms make it essential for system administrators, network engineers, and security professionals. Whether capturing packets for offline analysis, investigating real-time security incidents, or validating network configurations, tcpdump provides the packet-level visibility needed to understand and resolve complex network issues.

Key takeaways:

  • BPF filters enable precise packet capture at kernel level
  • Protocol knowledge enhances effective analysis
  • Performance optimization prevents system impact during capture
  • Security awareness protects sensitive data and ensures legal compliance
  • File operations support offline analysis and archival
  • Scripting capabilities enable automated monitoring and alerting
  • Combination with other tools (Wireshark, grep, awk) enhances analysis

Master tcpdump to gain deep network visibility, develop systematic troubleshooting approaches, and build expertise in packet-level network analysis that applies across diverse environments and challenges.

For advanced scenarios, explore tshark for scriptable Wireshark functionality, ngrep for grep-like packet matching, and integration with intrusion detection systems like Suricata or Snort for comprehensive network security monitoring.