Skip to main content
โšก Calmops

Tcpdump Advanced Usage: Command-Line Packet Analysis Mastery 2026

Introduction

Tcpdump remains the foundational tool for command-line packet capture, offering lightweight, efficient packet analysis without graphical overhead. While tools like Wireshark provide rich GUIs, tcpdump excels in server environments, automation scripts, and situations requiring remote analysis over SSH.

This comprehensive guide covers advanced tcpdump usage including complex BPF filters, performance optimization, output formatting, scripting integration, and production troubleshooting techniques that make tcpdump an essential tool for every network professional.

Understanding BPF Syntax

Basic Filter Expressions

The Berkeley Packet Filter (BPF) syntax forms the foundation of tcpdump filtering. Understanding BPF enables precise traffic selection at the capture level, reducing disk I/O and simplifying analysis.

# Host-based filtering
tcpdump host 192.168.1.1
tcpdump src host 10.0.0.5
tcpdump dst host 10.0.0.5

# Network filtering (CIDR notation)
tcpdump net 192.168.0.0/24
tcpdump src net 10.0.0.0/8

# Port filtering
tcpdump port 80
tcpdump src port 443
tcpdump dst port 53

# Protocol filtering
tcpdump tcp
tcpdump udp
tcpdump icmp
tcpdump arp

Combining Expressions

Boolean operators create complex filters:

# AND - both conditions must match
tcpdump host 192.168.1.1 and port 80
tcpdump tcp and src port 443 and dst host 10.0.0.1

# OR - either condition matches
tcpdump port 80 or port 443
tcpdump host 192.168.1.1 or 192.168.1.2

# NOT - negate condition
tcpdump not port 22
tcpdump not arp and not icmp
tcpdump not host 192.168.1.1

# Complex expression
tcpdump 'tcp[tcpflags] & (tcp-syn|tcp-ack) != 0 and not src net 10.0.0.0/8'

Protocol Header Filtering

Access specific header fields using byte offsets:

# TCP flags (offset 13 in TCP header)
tcpdump 'tcp[13] & 2 != 0'           # SYN packets
tcpdump 'tcp[13] & 16 != 0'         # ACK packets
tcpdump 'tcp[13] & 18 != 0'         # SYN-ACK
tcpdump 'tcp[13] & 1 != 0'          # FIN
tcpdump 'tcp[13] & 8 != 0'          # PUSH

# ICMP type (offset 0 in ICMP header)
tcpdump 'icmp[0] == 8'               # Echo Request
tcpdump 'icmp[0] == 0'               # Echo Reply
tcpdump 'icmp[0] == 3'               # Destination Unreachable

# TCP/UDP port (offset for source port)
tcpdump 'tcp[0:2] == 80'             # Source port 80
tcpdump 'udp[2:2] == 53'             # Source port 53 (DNS)

Port Range Filtering

Filter ranges using comparison operators:

# Port ranges
tcpdump 'tcp[0:2] > 1023 and tcp[0:2] < 10000'
tcpdump 'udp[0:2] >= 32768'          # Ephemeral ports

# Specific port ranges
tcpdump 'tcp[0:2] >= 80 and tcp[0:2] <= 443'

Advanced Capture Techniques

Snapshot Length Optimization

The snapshot length (-s) controls how much of each packet is captured:

# Capture default (68 bytes - minimal for analysis)
tcpdump -i eth0

# Full packet capture
tcpdump -i eth0 -s 65535

# Optimal for most analysis (Ethernet MTU)
tcpdump -i eth0 -s 1514

# Quick capture for header analysis only
tcpdump -i eth0 -s 128

The -s 0 flag automatically uses the correct snapshot length for each interface, ensuring complete packet capture withoutๆตช่ดน.

Buffer and Ring Buffer Configuration

Prevent packet loss during high-speed captures with proper buffer configuration:

# Set capture buffer size (in MB)
tcpdump -i eth0 -B 64

# Ring buffer - 10 files of 100MB each
tcpdump -i eth0 -W 10 -C 100 -w capture.pcap

# Time-based rotation (every 5 minutes)
tcpdump -i eth0 -G 300 -w capture_%Y%m%d_%H%M.pcap

# Combined: 10 files max, 100MB each, rotate every 5 minutes
tcpdump -i eth0 -W 10 -C 100 -G 300 -w capture_%Y%m%d_%H%M.pcap

Immediate Mode and Promiscuous Mode

Control packet processing behavior:

# Immediate mode - no buffering (real-time display)
tcpdump -i eth0 -l | tee output.log

# Disable promiscuous mode
tcpdump -i eth0 -not promisc

# Promiscuous mode (default, explicit)
tcpdump -i eth0 -p

# Monitor mode (for wireless)
tcpdump -i wlan0 -I

Remote Capture

Capture packets on remote systems efficiently:

# Direct SSH capture (real-time)
ssh root@remote-host "tcpdump -i eth0 -w -" | tcpdump -r - -w local.pcap

# With capture filter
ssh root@remote-host "tcpdump -i eth0 -w - 'tcp port 80'" | tcpdump -r -

# Using SSH with compression for slow links
ssh -C root@remote-host "tcpdump -i eth0 -w -" | tcpdump -r -

For regular remote monitoring, consider setting up an SSH key-based authentication to avoid password prompts.

Multicast and VLAN Capture

Handle complex network configurations:

# Capture VLAN tagged packets
tcpdump -i eth0 -v

# Filter specific VLAN
tcpdump -i eth0 vlan 100

# Multi-VLAN capture
tcpdump -i eth0 'vlan 100 or vlan 200'

# Capture QinQ (VLAN stacking)
tcpdump -i eth0 -e

# Multicast traffic
tcpdump multicast
tcpdump ip multicast

Output Format Mastery

Verbose Output Levels

Control the amount of information displayed:

# Level 1 - Basic (default)
tcpdump -i eth0

# Level 2 - More details (-v)
tcpdump -i eth0 -v

# Level 3 - Full details (-vv)
tcpdump -i eth0 -vv

# Level 4 - Maximum (-vvv)
tcpdump -i eth0 -vvv

# Timestamp with microseconds
tcpdump -i eth0 -tttt

The -e flag adds link-layer header information:

# With Ethernet headers
tcpdump -i eth0 -e

Custom Output Formatting

Extract specific fields for parsing:

# Quick summary line per packet
tcpdump -i eth0 -q

# Hex and ASCII output
tcpdump -i eth0 -X
tcpdump -i eth0 -XX

# Absolute sequence numbers
tcpdump -i eth0 -S

# Print payload in hex (without ASCII)
tcpdump -i eth0 -hex

# Print only payload data
tcpdump -i eth0 -A

Creating Parseable Output

Generate output suitable for scripting:

# CSV-like output
tcpdump -i eth0 -tttt -l | tee output.txt

# Custom format with -e and timestamp
tcpdump -i eth0 -e -n -tt '|%p|%s|%d|%r|'

# Extract specific fields for analysis
tcpdump -i eth0 -n -l | awk '{print $3, $5, $9}'

# JSON output (with additional tools)
tcpdump -i eth0 -n -l | jq -R 'split(" ") | {src: .[2], dst: .[4], info: .[length-1]}'

Saving and Reading Captures

Work with PCAP files efficiently:

# Save to file
tcpdump -i eth0 -w capture.pcap

# Append to existing file
tcpdump -i eth0 -w capture.pcap -C 10

# Read from file
tcpdump -r capture.pcap

# Read with display filter
tcpdump -r capture.pcap host 192.168.1.1

# Read with BPF filter (faster)
tcpdump -r capture.pcap -R 'ip.addr == 192.168.1.1'

# Compress captures (for long-term storage)
tcpdump -i eth0 -w - | gzip > capture.pcap.gz

Practical Analysis Examples

HTTP Traffic Analysis

Analyze web traffic patterns:

# Capture HTTP traffic
tcpdump -i eth0 port 80 -w http.pcap

# View HTTP requests
tcpdump -i eth0 -vv -A 'tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x47455420'

# Capture specific domains (requires TLS inspection)
tcpdump -i eth0 -s 0 host example.com

# HTTP error responses
tcpdump -i eth0 'tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x48545420' | grep " 4[0-9][0-9] "

DNS Query Analysis

Monitor DNS resolution:

# Capture DNS queries
tcpdump -i eth0 port 53 -w dns.pcap

# DNS queries only
tcpdump -i eth0 'udp[10:1] & 0x80 = 0'

# AAAA queries (IPv6)
tcpdump -i eth0 'udp[10:1] & 0x80 = 0 and udp[22:2] = 0x001c'

# DNS responses with large answers
tcpdump -i eth0 'udp[10:1] & 0x80 != 0 and udp[20:2] > 100'

TLS/SSL Handshake Analysis

Analyze encrypted connections:

# Capture TLS handshakes
tcpdump -i eth0 port 443 -w tls.pcap

# TLS ClientHello packets
tcpdump -i eth0 -X 'tcp[((tcp[12:1] & 0xf0) >> 2):5] = 0x16030300'

# TLS ServerHello
tcpdump -i eth0 -X 'tcp[((tcp[12:1] & 0xf0) >> 2):5] = 0x16030300'

# All TLS records
tcpdump -i eth0 port 443 -T tls

Network Troubleshooting

Common troubleshooting scenarios:

# TCP connection issues
tcpdump -i eth0 'tcp[tcpflags] & (tcp-syn|tcp-fin|tcp-rst) != 0'

# Fragmented packets
tcpdump -i eth0 'ip[6:2] & 0x4000 != 0'

# Large packets (potential issues)
tcpdump -i eth0 'ip[2:2] > 1400'

# Unusual TTL values
tcpdump -i eth0 'ip[8] < 5 or ip[8] > 128'

# Broadcast/multicast storms
tcpdump -i eth0 -c 100 'broadcast or multicast'

Security Analysis

Detect potential security issues:

# Port scanning detection
tcpdump -i eth0 'tcp[13] & 2 != 0' | awk '{print $5}' | sort | uniq -c | sort -rn

# SYN flood detection
tcpdump -i eth0 'tcp[13] = 2' | pv -l > /tmp/syn_rate.txt

# Cleartext passwords (HTTP Basic Auth)
tcpdump -i eth0 port 80 | grep -i "authorization: basic"

# Suspicious payloads
tcpdump -i eth0 -X | grep -i "password\|passwd\|pwd"

# Unusual protocols on standard ports
tcpdump -i eth0 -n 'port 80 and not tcp[13:1] & 7 = 0'

Scripting and Automation

Real-Time Monitoring Scripts

#!/bin/bash
# monitor-traffic.sh - Real-time traffic monitoring

INTERFACE="${1:-eth0}"
THRESHOLD="${2:-1000}"

tcpdump -i "$INTERFACE" -l | while read line; do
    count=$(echo "$line" | wc -c)
    if [ "$count" -gt "$THRESHOLD" ]; then
        echo "$(date): Large packet detected"
        echo "$line"
    fi
done

Automated Capture Scripts

#!/bin/bash
# capture-with-rotation.sh - Capture with automatic rotation

INTERFACE="${1:-eth0}"
OUTDIR="${2:-/tmp/captures}"
DURATION="${3:-300}"  # seconds
MAXFILES="${4:-100}"

mkdir -p "$OUTDIR"

tcpdump -i "$INTERFACE" \
    -W "$MAXFILES" \
    -C 100 \
    -G "$DURATION" \
    -w "$OUTDIR/capture_%Y%m%d_%H%M.pcap" \
    -Z root &

PID=$!
echo "Capture started: $PID"

# Cleanup on exit
trap "kill $PID" EXIT INT TERM

Traffic Analysis Scripts

#!/bin/bash
# analyze-pcap.sh - Analyze captured traffic

FILE="$1"

if [ -z "$FILE" ]; then
    echo "Usage: $0 <pcap-file>"
    exit 1
fi

echo "=== Traffic Summary ==="
tcpdump -r "$FILE" -q | tail -1

echo -e "\n=== Protocol Distribution ==="
tcpdump -r "$FILE" -q | awk '{print $NF}' | sort | uniq -c | sort -rn | head -10

echo -e "\n=== Top Source IPs ==="
tcpdump -r "$FILE" -nn -q | awk '{print $3}' | cut -d. -f1-4 | sort | uniq -c | sort -rn | head -10

echo -e "\n=== Top Destination IPs ==="
tcpdump -r "$FILE" -nn -q | awk '{print $5}' | cut -d. -f1-4 | sort | uniq -c | sort -rn | head -10

echo -e "\n=== TCP Issues ==="
tcpdump -r "$FILE" 'tcp[13] & 2 != 0' | wc -l
echo "SYN packets detected"

Performance Monitoring

#!/bin/bash
# monitor-throughput.sh - Monitor network throughput

INTERFACE="${1:-eth0}"

echo "Monitoring $INTERFACE... Press Ctrl+C to stop"
echo "Time Packets Bytes"

while true; do
    stats=$(tcpdump -i "$INTERFACE" -c 1000 -q 2>/dev/null | tail -1)
    if [ -n "$stats" ]; then
        echo "$(date +%H:%M:%S) $stats"
    fi
    sleep 1
done

Performance Optimization

Minimizing Packet Loss

High-speed networks require careful configuration:

# Increase buffer size
sysctl -w net.core.rmem_max=16777216
sysctl -w net.core.rmem_default=16777216

# Increase interface buffer
ifconfig eth0 txqueuelen 10000

# Disable reverse path filtering
sysctl -w net.ipv4.conf.all.rp_filter=0
sysctl -w net.ipv4.conf.eth0.rp_filter=0

# Increase pf_ring buffer
tcpdump -i eth0 -b 128

Hardware Offloading

Disable offloading features that interfere with capture:

# Disable NIC offloading
ethtool -K eth0 tso off
ethtool -K eth0 gso off
ethtool -K eth0 gro off
ethtool -K eth0 rx off
ethtool -K eth0 tx off

# Verify settings
ethtool -k eth0

Parallel Capture

For multi-interface monitoring:

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

INTERFACES=(eth0 eth1 eth2)

for iface in "${INTERFACES[@]}"; do
    tcpdump -i "$iface" -w "/tmp/${iface}.pcap" -C 100 -W 10 &
done

wait

Integration with Other Tools

Converting to Wireshark Format

# PCAP to PCAPNG
editcap -F pcapng input.pcap output.pcapng

# Compress legacy format
editcap -F libpcap input.pcap output.pcap

# Extract specific time range
editcap -r input.pcap output.pcap 0-100

Pipeline with Analysis Tools

# Feed to NetworkMiner
tcpdump -i eth0 -w - | networkminer -

# Real-time Zeek analysis
tcpdump -i eth0 -w - | zeek -r -

# Feed to SiLK
tcpdump -i eth0 -w - | rw-append --

Statistics Generation

# Basic statistics
tcpdump -i eth0 -r capture.pcap -z stats

# Throughput over time
tcpdump -i eth0 -w - | pv -L 10m > /dev/null

# Connection tracking
tcpdump -i eth0 -nn -c 10000 | awk '{print $3, $5}' | cut -d. -f1-4 | sort | uniq | wc -l

Troubleshooting Common Issues

Permission Denied

# Add user to pcap group
sudo usermod -a -G pcap $USER

# Use sudo for raw socket access
sudo tcpdump -i eth0

# Create pcap group
sudo groupadd pcap
sudo chgrp pcap /usr/sbin/tcpdump
sudo chmod 750 /usr/sbin/tcpdump

Interface Not Found

# List available interfaces
tcpdump -D

# List with details
ip link show

# Create dummy interface for testing
ip link add dummy0 type dummy
ip addr add 10.0.0.1/24 dev dummy0
ip link set dummy0 up

High CPU Usage

# Reduce sampling
tcpdump -i eth0 -s 128

# Use pfring
tcpdump -i eth0 -P

# Increase buffer
tcpdump -i eth0 -B 128

External Resources

Conclusion

Tcpdump remains an indispensable tool for network analysis, offering unmatched flexibility for command-line packet capture and analysis. Master these advanced techniques to efficiently debug network issues, analyze traffic patterns, and monitor network security. Combined with other tools in your toolkit, tcpdump provides the foundation for professional network analysis and troubleshooting.

Comments