Picture of NOC
|

How to Monitor Network Traffic in Linux: Real-Time Analysis with tcpdump and Wireshark

Network traffic monitoring forms the backbone of effective infrastructure management. Linux systems provide powerful, built-in capabilities for capturing and analyzing network packets in real-time.

Network engineers and system administrators rely on packet-level analysis to:

  • Diagnose connectivity issues between systems
  • Identify performance bottlenecks
  • Detect security threats and anomalies
  • Verify application behavior
  • Validate network configuration changes

Linux offers distinct advantages for network monitoring:

  • Native kernel support for packet capture
  • No licensing costs for monitoring tools
  • Scriptable interfaces for automation
  • Remote access capabilities via SSH
  • Minimal resource overhead compared to proprietary solutions

tcpdump vs Wireshark: Quick Comparison

Feature tcpdump Wireshark
Interface Command-line Graphical (GUI)
Resource Usage Minimal Moderate to High
Remote Capture Native via SSH Requires additional setup
Real-time Analysis Basic Advanced
Learning Curve Moderate Gentle

This guide teaches you to leverage both tools effectively for comprehensive network analysis.

Understanding Network Traffic Monitoring Fundamentals in Linux

How Packet Capture Works in Linux

Linux captures network packets through a multi-layer architecture:

  1. Network Interface Card (NIC) receives packets from the network
  2. Device driver passes packets to the kernel
  3. Kernel copies packets to userspace via AF_PACKET socket
  4. libpcap library provides API for packet capture applications
  5. Applications (tcpdump/Wireshark) process captured packets

Enable Promiscuous Mode

Promiscuous mode allows the NIC to capture all packets on the network segment, not just those destined for your host.

# Check current mode
ip link show eth0

# Enable promiscuous mode
sudo ip link set eth0 promisc on

# Verify the change
ip link show eth0 | grep -i promisc

Berkeley Packet Filter (BPF)

BPF filters packets in kernel space, reducing overhead by only passing relevant packets to userspace.

BPF filter example structure:

# Basic BPF filter syntax
protocol[offset:size] operator value

# Example: Capture packets with TCP destination port 443
tcp[2:2] = 443

Prerequisites and System Requirements

Required Permissions

  • Root access or sudo privileges for packet capture
  • CAP_NET_RAW and CAP_NET_ADMIN capabilities
# Grant capture capabilities to tcpdump (alternative to running as root)
sudo setcap cap_net_raw,cap_net_admin=eip /usr/sbin/tcpdump

# Verify capabilities
getcap /usr/sbin/tcpdump

Check System Dependencies

# Verify libpcap installation
ldconfig -p | grep libpcap

# Check kernel support for packet capture
ls -la /sys/class/net/

# List available network interfaces
ip link show

# Check interface statistics
cat /proc/net/dev

Performance Considerations

  • Buffer size: Increase for high-traffic networks (default: 2MB)
  • CPU affinity: Dedicate CPU cores for capture process
  • Storage speed: Use SSD for writing large capture files
  • Memory allocation: Reserve sufficient RAM for packet buffers
# Increase kernel buffer size
sudo sysctl -w net.core.rmem_max=134217728
sudo sysctl -w net.core.rmem_default=134217728

# Make changes persistent
echo "net.core.rmem_max=134217728" | sudo tee -a /etc/sysctl.conf
echo "net.core.rmem_default=134217728" | sudo tee -a /etc/sysctl.conf

Mastering tcpdump for Command-Line Network Analysis

Getting Started with tcpdump Installation and Basic Usage

Installation Commands

# RHEL/CentOS/Fedora
sudo yum install tcpdump

# Ubuntu/Debian
sudo apt-get update
sudo apt-get install tcpdump

# SUSE/openSUSE
sudo zypper install tcpdump

# Arch Linux
sudo pacman -S tcpdump

Basic tcpdump Syntax

tcpdump [options] [filter expression]

Essential Command Options

  • -i interface: Specify capture interface
  • -n: Don’t resolve hostnames
  • -nn: Don’t resolve hostnames or ports
  • -c count: Capture specific number of packets
  • -w file.pcap: Write packets to file
  • -r file.pcap: Read packets from file
  • -v, -vv, -vvv: Increase verbosity levels
  • -X: Print packet contents in hex and ASCII
  • -A: Print packet contents in ASCII
  • -s snaplen: Capture bytes per packet (0 = all)

Basic Capture Examples

# Capture all traffic on eth0
sudo tcpdump -i eth0

# Capture 100 packets and save to file
sudo tcpdump -i eth0 -c 100 -w capture.pcap

# Capture with timestamps and no name resolution
sudo tcpdump -i eth0 -nn -tttt

# Capture full packet content
sudo tcpdump -i eth0 -s 0 -X

Essential tcpdump Filters and Real-Time Capture Techniques

Host-Based Filtering

# Capture traffic to/from specific host
sudo tcpdump -i eth0 host 192.168.1.100

# Capture traffic from source host
sudo tcpdump -i eth0 src host 10.0.0.1

# Capture traffic to destination host
sudo tcpdump -i eth0 dst host 10.0.0.2

# Capture traffic between two hosts
sudo tcpdump -i eth0 host 192.168.1.1 and host 192.168.1.2

Port and Protocol Filtering

# Capture HTTP traffic (port 80)
sudo tcpdump -i eth0 port 80

# Capture HTTPS traffic (port 443)
sudo tcpdump -i eth0 port 443

# Capture DNS traffic (port 53)
sudo tcpdump -i eth0 port 53

# Capture SSH traffic
sudo tcpdump -i eth0 port 22

# Capture traffic on port range
sudo tcpdump -i eth0 portrange 80-443

# Capture specific protocol
sudo tcpdump -i eth0 icmp
sudo tcpdump -i eth0 tcp
sudo tcpdump -i eth0 udp

Complex Filter Expressions

# Capture HTTP traffic from specific subnet
sudo tcpdump -i eth0 'src net 192.168.1.0/24 and dst port 80'

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

# Capture TCP SYN packets
sudo tcpdump -i eth0 'tcp[tcpflags] & (tcp-syn) != 0'

# Capture TCP packets with specific flags
sudo tcpdump -i eth0 'tcp[tcpflags] & (tcp-syn|tcp-fin) != 0'

# Capture packets larger than 1000 bytes
sudo tcpdump -i eth0 'greater 1000'

# Capture ICMP echo requests and replies
sudo tcpdump -i eth0 'icmp[icmptype] = 8 or icmp[icmptype] = 0'

Advanced tcpdump Features for Network Troubleshooting

Rotating Capture Files

# Rotate files every 100MB, keep 10 files
sudo tcpdump -i eth0 -w capture.pcap -C 100 -W 10

# Rotate files every hour
sudo tcpdump -i eth0 -w 'capture-%Y%m%d-%H%M%S.pcap' -G 3600

# Combine size and time rotation
sudo tcpdump -i eth0 -w capture.pcap -C 100 -G 3600 -W 48

Performance Optimization

# Use larger buffer size (in KB)
sudo tcpdump -i eth0 -B 4096

# Disable DNS resolution for better performance
sudo tcpdump -i eth0 -nn

# Capture only first 96 bytes of each packet
sudo tcpdump -i eth0 -s 96

# Use immediate mode (disable buffering)
sudo tcpdump -i eth0 --immediate-mode

Timestamp Options

# Default timestamp
sudo tcpdump -i eth0

# Timestamp with date
sudo tcpdump -i eth0 -tttt

# Unix timestamp
sudo tcpdump -i eth0 -tt

# Microsecond precision
sudo tcpdump -i eth0 -ttt

# Nanosecond precision
sudo tcpdump -i eth0 --time-stamp-precision=nano

Leveraging Wireshark for GUI-Based Network Traffic Analysis on Linux

Installing and Configuring Wireshark on Linux Systems

Installation Methods

# Ubuntu/Debian
sudo apt-get update
sudo apt-get install wireshark
sudo apt-get install tshark  # Command-line version

# RHEL/CentOS 8+
sudo dnf install wireshark
sudo dnf install wireshark-cli

# Fedora
sudo dnf install wireshark
sudo dnf install wireshark-cli

# Arch Linux
sudo pacman -S wireshark-qt
sudo pacman -S wireshark-cli

Configure Non-Root Capture Permissions

# Add user to wireshark group
sudo usermod -aG wireshark $USER

# Reconfigure wireshark for non-root capture
sudo dpkg-reconfigure wireshark-common
# Select "Yes" when prompted

# Grant capabilities to dumpcap
sudo setcap cap_net_raw,cap_net_admin+eip /usr/bin/dumpcap

# Verify permissions
getcap /usr/bin/dumpcap

# Log out and back in for group changes to take effect

Remote Capture Setup

# Method 1: SSH pipe to Wireshark
ssh root@remote-server 'tcpdump -i eth0 -w - -s 0' | wireshark -k -i -

# Method 2: Using dumpcap remotely
ssh root@remote-server 'dumpcap -i eth0 -w - -f "port 80"' | wireshark -k -i -

# Method 3: Save remotely and transfer
ssh root@remote-server 'tcpdump -i eth0 -w /tmp/capture.pcap -c 1000'
scp root@remote-server:/tmp/capture.pcap ./
wireshark capture.pcap

Real-Time Traffic Monitoring with Wireshark

Capture Filter Examples

# Basic capture filters (BPF syntax)
host 192.168.1.1
port 80
tcp port 443
udp port 53
net 10.0.0.0/8
src host 192.168.1.100
dst port 3306

Display Filter Examples

# Common display filters
ip.addr == 192.168.1.1
tcp.port == 80
http.request.method == "GET"
dns.qry.name contains "google"
tcp.flags.syn == 1
tcp.analysis.retransmission
frame.len > 1500
http.response.code == 404
ssl.handshake.type == 1

Color Rules Configuration

Create custom coloring rules for quick visual identification:

  1. View → Coloring Rules
  2. Click “+” to add new rule
  3. Set filter and colors

Example color rules:

# HTTP traffic - Light Green
http

# HTTPS traffic - Light Blue
ssl || tls

# DNS queries - Yellow
dns.flags.response == 0

# TCP retransmissions - Red
tcp.analysis.retransmission

# SYN packets - Orange
tcp.flags.syn == 1 && tcp.flags.ack == 0

Following TCP Streams

  1. Right-click on any TCP packet
  2. Select “Follow” → “TCP Stream”
  3. View entire conversation
  4. Save or filter the stream

Advanced Wireshark Analysis Techniques

Statistics and Analysis Tools

  • Statistics → Protocol Hierarchy: View traffic breakdown by protocol
  • Statistics → Conversations: Analyze traffic between endpoints
  • Statistics → IO Graph: Visualize traffic over time
  • Statistics → Flow Graph: View packet flow sequence
  • Analysis → Expert Information: Identify potential issues

Custom Column Configuration

# Add custom columns via GUI:
1. Right-click column header
2. Select "Column Preferences"
3. Add new column
4. Set field name (e.g., http.request.uri, tcp.stream, ip.ttl)

# Useful custom columns:
tcp.stream          - TCP stream index
http.request.uri    - HTTP request URI
dns.qry.name       - DNS query name
tcp.time_relative  - Relative time in TCP stream
frame.len          - Frame length
ip.ttl             - IP Time to Live

Command-Line Analysis with tshark

# Basic tshark usage
tshark -i eth0 -f "port 80"

# Read pcap file
tshark -r capture.pcap

# Apply display filter
tshark -r capture.pcap -Y "http.request"

# Export specific fields
tshark -r capture.pcap -T fields -e ip.src -e ip.dst -e tcp.port

# Generate statistics
tshark -r capture.pcap -z io,stat,1

# Export to CSV
tshark -r capture.pcap -T fields -e frame.time -e ip.src -e ip.dst -E header=y -E separator=, > output.csv

# Decode as specific protocol
tshark -r capture.pcap -d tcp.port==8080,http

Practical Use Cases: Real-World Network Monitoring Scenarios

Troubleshooting Network Performance Issues

Identify TCP Retransmissions

# tcpdump - Capture retransmitted packets
sudo tcpdump -i eth0 'tcp[tcpflags] & (tcp-rst) != 0'

# Wireshark display filter
tcp.analysis.retransmission || tcp.analysis.fast_retransmission

# tshark - Count retransmissions
tshark -r capture.pcap -Y "tcp.analysis.retransmission" | wc -l

Detect MTU Issues

# Capture ICMP "Fragmentation Needed" messages
sudo tcpdump -i eth0 'icmp[icmptype] = 3 and icmp[icmpcode] = 4'

# Capture packets with Don't Fragment bit set
sudo tcpdump -i eth0 'ip[6] & 0x40 != 0'

# Check for packets near MTU size
sudo tcpdump -i eth0 'greater 1400'

Monitor Bandwidth Usage

# Capture and analyze top talkers
sudo tcpdump -i eth0 -nn -c 1000 > traffic.txt
awk '{print $3}' traffic.txt | cut -d. -f1-4 | sort | uniq -c | sort -rn | head -10

# Monitor specific application traffic
sudo tcpdump -i eth0 -nn port 3306 -c 100

Security Monitoring and Incident Response

Detect Port Scanning

# Capture SYN packets without established connections
sudo tcpdump -i eth0 'tcp[tcpflags] == tcp-syn'

# Detect SYN flood attack patterns
sudo tcpdump -i eth0 -nn 'tcp[tcpflags] == tcp-syn' | awk '{print $3}' | sort | uniq -c | sort -rn

# Wireshark filter for port scan detection
tcp.flags.syn==1 && tcp.flags.ack==0 && tcp.window_size <= 1024

Identify Suspicious DNS Queries

# Capture all DNS traffic
sudo tcpdump -i eth0 -nn port 53

# Look for unusual TXT record queries
sudo tcpdump -i eth0 -nn 'udp port 53' -A | grep -E "TXT|txt"

# Monitor DNS responses with multiple answers
tshark -i eth0 -Y "dns.count.answers > 5"

Capture Potential Malware Communication

# Monitor non-standard ports
sudo tcpdump -i eth0 -nn 'not port 22 and not port 80 and not port 443 and not port 53'

# Capture traffic to suspicious IP ranges
sudo tcpdump -i eth0 -nn 'dst net 185.0.0.0/8 or dst net 45.0.0.0/8'

# Look for periodic beaconing
tshark -r capture.pcap -T fields -e frame.time_relative -e ip.src -e ip.dst | awk '$1 % 60 < 1'

Application and Protocol Analysis

HTTP/HTTPS Traffic Inspection

# Capture HTTP GET requests
sudo tcpdump -i eth0 -nn -A -s0 'tcp port 80 and tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x47455420'

# Extract URLs from HTTP traffic
sudo tcpdump -i eth0 -nn -A -s0 'tcp port 80' | grep -E "GET|POST|Host:"

# Monitor HTTP response codes
tshark -i eth0 -Y "http.response" -T fields -e http.response.code -e http.request.uri

Database Query Analysis

# MySQL traffic analysis
sudo tcpdump -i eth0 -nn -X -s0 'tcp port 3306'

# PostgreSQL traffic
sudo tcpdump -i eth0 -nn -X -s0 'tcp port 5432'

# Extract query patterns
tshark -i eth0 -Y "mysql.query" -T fields -e mysql.query

VoIP Quality Monitoring

# Capture SIP traffic
sudo tcpdump -i eth0 -nn port 5060

# Capture RTP traffic (common port range)
sudo tcpdump -i eth0 -nn portrange 10000-20000

# Analyze jitter and packet loss in Wireshark
# Telephony → RTP → RTP Streams
# Select stream → Analyze

Combining tcpdump and Wireshark for Comprehensive Network Analysis

Workflow Integration Strategies

Remote Capture, Local Analysis

# Capture on remote server with tcpdump
ssh admin@remote-server 'sudo tcpdump -i eth0 -w - "port 80"' > local_capture.pcap

# Open in Wireshark for analysis
wireshark local_capture.pcap

# Real-time remote capture to Wireshark
ssh admin@remote-server 'sudo tcpdump -i eth0 -w - -U "port 443"' | wireshark -k -i -

Automated Capture Scripts

#!/bin/bash
# rotating_capture.sh - Automated rotating packet capture

INTERFACE="eth0"
CAPTURE_DIR="/var/log/pcap"
FILESIZE="100"  # MB
FILECOUNT="24"  # Number of files to keep
FILTER="tcp port 80 or tcp port 443"

# Create directory if not exists
mkdir -p $CAPTURE_DIR

# Start rotating capture
tcpdump -i $INTERFACE -w $CAPTURE_DIR/capture-%Y%m%d-%H%M%S.pcap \
        -W $FILECOUNT -C $FILESIZE "$FILTER"

Batch Processing Script

#!/bin/bash
# analyze_pcaps.sh - Process multiple pcap files

PCAP_DIR="/var/log/pcap"
OUTPUT_DIR="/var/log/analysis"

mkdir -p $OUTPUT_DIR

for pcap in $PCAP_DIR/*.pcap; do
    basename=$(basename "$pcap" .pcap)
    
    # Extract statistics
    echo "Processing $pcap..."
    
    # Get top talkers
    tshark -r "$pcap" -z conv,ip -q > "$OUTPUT_DIR/${basename}_conversations.txt"
    
    # Extract HTTP requests
    tshark -r "$pcap" -Y "http.request" -T fields \
           -e frame.time -e ip.src -e http.host -e http.request.uri \
           > "$OUTPUT_DIR/${basename}_http_requests.csv"
    
    # Find TCP errors
    tshark -r "$pcap" -Y "tcp.analysis.flags" -T fields \
           -e frame.time -e ip.src -e ip.dst -e tcp.analysis.flags \
           > "$OUTPUT_DIR/${basename}_tcp_errors.csv"
done

Performance Optimization for High-Speed Networks

Buffer Tuning Configuration

# System-wide buffer settings
sudo sysctl -w net.core.rmem_max=134217728
sudo sysctl -w net.core.wmem_max=134217728
sudo sysctl -w net.core.netdev_max_backlog=5000
sudo sysctl -w net.ipv4.tcp_rmem="4096 87380 134217728"
sudo sysctl -w net.ipv4.tcp_wmem="4096 65536 134217728"

# tcpdump with optimized buffer
sudo tcpdump -i eth0 -B 65536 -w capture.pcap

# tshark with larger buffer
tshark -i eth0 -B 64 -w capture.pcap

CPU Affinity Settings

# Set CPU affinity for tcpdump
sudo taskset -c 2,3 tcpdump -i eth0 -w capture.pcap

# Check CPU usage per core
mpstat -P ALL 1

# Set IRQ affinity for network card
echo 4 | sudo tee /proc/irq/24/smp_affinity

PF_RING for Enhanced Performance

# Install PF_RING
git clone https://github.com/ntop/PF_RING.git
cd PF_RING/kernel
make
sudo make install

# Load PF_RING module
sudo modprobe pf_ring

# Use PF_RING-aware tcpdump
sudo tcpdump -i eth0@0 -w capture.pcap

Alternative and Complementary Linux Network Monitoring Tools

Overview of Additional Tools

tshark – Command-Line Wireshark

# Live capture with display filter
tshark -i eth0 -Y "tcp.port == 443"

# Protocol hierarchy statistics
tshark -r capture.pcap -z io,phs -q

# Export specific conversations
tshark -r capture.pcap -z conv,tcp -q

iftop – Bandwidth Usage Monitor

# Install iftop
sudo apt-get install iftop  # Debian/Ubuntu
sudo yum install iftop      # RHEL/CentOS

# Monitor interface bandwidth
sudo iftop -i eth0

# Show port numbers
sudo iftop -i eth0 -P

# Filter specific network
sudo iftop -i eth0 -F 192.168.1.0/24

nethogs – Per-Process Bandwidth Monitor

# Install nethogs
sudo apt-get install nethogs

# Monitor bandwidth per process
sudo nethogs eth0

# Update every 5 seconds
sudo nethogs -d 5 eth0

ss – Socket Statistics

# Show all TCP connections
ss -tan

# Show listening ports
ss -tln

# Show process using sockets
ss -tanp

# Filter by state
ss -tan state established

# Show timer information
ss -tanto

ngrep – Network Grep

# Install ngrep
sudo apt-get install ngrep

# Search for pattern in traffic
sudo ngrep -q "GET|POST" tcp port 80

# Case-insensitive search
sudo ngrep -i "password" port 3306

# Save matched packets
sudo ngrep -O matched.pcap "error" port 80

tcpflow – TCP Session Reconstruction

# Install tcpflow
sudo apt-get install tcpflow

# Reconstruct TCP sessions from pcap
tcpflow -r capture.pcap

# Output to specific directory
tcpflow -r capture.pcap -o output_dir/

# Console output for text streams
tcpflow -c -r capture.pcap

Tool Selection Matrix

Use Case Best Tool Alternative
Quick packet capture tcpdump tshark
Deep packet analysis Wireshark tshark with filters
Bandwidth monitoring iftop nethogs
Connection monitoring ss netstat
Pattern searching ngrep tcpdump with grep
Session reconstruction tcpflow Wireshark Follow Stream

Best Practices and Pro Tips for Effective Network Traffic Monitoring

Security and Privacy Considerations

Legal and Compliance Requirements

  • Obtain written authorization before capturing network traffic
  • Document the scope of monitoring activities
  • Comply with data protection regulations (GDPR, HIPAA, PCI-DSS)
  • Inform users when monitoring includes personal data
  • Establish retention policies for captured data

Secure PCAP File Handling

# Encrypt captured files
tcpdump -i eth0 -w - | openssl enc -aes-256-cbc -salt -out capture.enc

# Decrypt for analysis
openssl enc -d -aes-256-cbc -in capture.enc | tcpdump -r -

# Set appropriate file permissions
chmod 600 /path/to/capture.pcap
chown root:netadmins /path/to/capture.pcap

# Secure deletion
shred -vfz -n 3 sensitive_capture.pcap

Access Control Implementation

# Create dedicated group for packet capture
sudo groupadd pcap-users
sudo usermod -a -G pcap-users analyst1

# Set capabilities for group access
sudo setcap cap_net_raw,cap_net_admin=eip /usr/sbin/tcpdump
sudo chgrp pcap-users /usr/sbin/tcpdump

# Audit logging for capture activities
echo "$(date): $USER started packet capture on $INTERFACE" >> /var/log/pcap_audit.log

Documentation and Methodology

Filter Library Template

# /etc/tcpdump/filters.conf
# Common tcpdump filters library

# Network segments
INTERNAL_NET="192.168.0.0/16"
DMZ_NET="10.10.10.0/24"
EXTERNAL_NET="not (src net $INTERNAL_NET or src net $DMZ_NET)"

# Service filters
WEB_TRAFFIC="tcp port 80 or tcp port 443"
MAIL_TRAFFIC="tcp port 25 or tcp port 587 or tcp port 993"
DNS_TRAFFIC="udp port 53 or tcp port 53"
DATABASE_TRAFFIC="tcp port 3306 or tcp port 5432"

# Security filters
SCAN_DETECT="tcp[tcpflags] & (tcp-syn) != 0 and tcp[tcpflags] & (tcp-ack) = 0"
ICMP_UNUSUAL="icmp[icmptype] != 8 and icmp[icmptype] != 0"

Capture Procedure Template

#!/bin/bash
# Standard packet capture procedure

# Variables
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
CASE_ID="INC001234"
ANALYST="$USER"
INTERFACE="eth0"
DURATION="300"  # seconds

# Pre-capture documentation
echo "=== Packet Capture Log ===" > capture_${CASE_ID}.log
echo "Case ID: $CASE_ID" >> capture_${CASE_ID}.log
echo "Analyst: $ANALYST" >> capture_${CASE_ID}.log
echo "Start Time: $(date)" >> capture_${CASE_ID}.log
echo "Interface: $INTERFACE" >> capture_${CASE_ID}.log
echo "Duration: $DURATION seconds" >> capture_${CASE_ID}.log

# Execute capture
timeout $DURATION tcpdump -i $INTERFACE -w ${CASE_ID}_${TIMESTAMP}.pcap

# Post-capture documentation
echo "End Time: $(date)" >> capture_${CASE_ID}.log
echo "File: ${CASE_ID}_${TIMESTAMP}.pcap" >> capture_${CASE_ID}.log
echo "Size: $(du -h ${CASE_ID}_${TIMESTAMP}.pcap | cut -f1)" >> capture_${CASE_ID}.log
echo "Packet Count: $(tcpdump -r ${CASE_ID}_${TIMESTAMP}.pcap 2>/dev/null | wc -l)" >> capture_${CASE_ID}.log

Analysis Checklist

  1. Validate capture integrity
    • Check file size and packet count
    • Verify timestamp accuracy
    • Confirm no dropped packets
  2. Initial assessment
    • Protocol hierarchy analysis
    • Top talkers identification
    • Conversation summary
  3. Detailed analysis
    • Apply relevant display filters
    • Check expert information
    • Follow suspicious streams
  4. Documentation
    • Export relevant packets
    • Screenshot important findings
    • Create analysis report

Common Pitfalls and Troubleshooting tcpdump/Wireshark Issues

Permission Denied Errors

Problem: Cannot capture packets without root

# Error message
tcpdump: eth0: You don't have permission to capture on that device

# Solution 1: Use sudo
sudo tcpdump -i eth0

# Solution 2: Set capabilities
sudo setcap cap_net_raw,cap_net_admin=eip /usr/sbin/tcpdump

# Solution 3: Add user to wireshark group (Wireshark only)
sudo usermod -a -G wireshark $USER
# Log out and back in

Dropped Packets During Capture

Problem: Kernel dropped packets message

# Check for dropped packets
tcpdump -i eth0 -nn -c 1000 2>&1 | grep -i dropped

# Solution 1: Increase buffer size
sudo tcpdump -i eth0 -B 10240

# Solution 2: Reduce capture overhead
sudo tcpdump -i eth0 -nn -s 96

# Solution 3: Optimize system buffers
sudo sysctl -w net.core.rmem_max=26214400
sudo sysctl -w net.core.rmem_default=26214400

Interface Not Showing Up

Problem: Network interface not available for capture

# List all interfaces
ip link show
ifconfig -a
tcpdump -D

# Bring interface up
sudo ip link set eth0 up

# Check if interface exists in namespace
ip netns list
ip netns exec  ip link show

# For virtual interfaces (Docker, VMs)
sudo tcpdump -i docker0
sudo tcpdump -i veth*

Performance Degradation

Problem: System slow during capture

# Monitor resource usage
top -p $(pgrep tcpdump)
iostat -x 1
vmstat 1

# Solutions:
# 1. Limit capture rate
sudo tcpdump -i eth0 --snapshot-length 64

# 2. Use BPF filter to reduce traffic
sudo tcpdump -i eth0 'tcp port 80'

# 3. Write to memory filesystem
sudo tcpdump -i eth0 -w /dev/shm/capture.pcap

# 4. Use ring buffer mode
sudo tcpdump -i eth0 -W 10 -C 100 -w capture.pcap

Interpreting Misleading Data

TCP Sequence Number Wrapping

# Large sequence numbers might wrap
# Use relative sequence numbers in Wireshark:
# Edit → Preferences → Protocols → TCP → Relative sequence numbers

# In tshark
tshark -r capture.pcap -o tcp.relative_sequence_numbers:TRUE

Checksum Errors on Capture Host

# Disable checksum validation (offloading false positives)
# In Wireshark:
# Edit → Preferences → Protocols → IPv4/TCP/UDP → Validate checksum: FALSE

# Check NIC offloading settings
ethtool -k eth0 | grep checksum

# Disable checksum offloading if needed
sudo ethtool -K eth0 rx off tx off

Timestamp Issues

# Verify system time
timedatectl status

# Sync time before capture
sudo ntpdate -s time.nist.gov

# Use consistent timestamp format
tcpdump -i eth0 -tttt  # Human readable with date
tcpdump -i eth0 -tt    # Unix timestamp

Conclusion: Building Your Network Monitoring Expertise

Key Takeaways

  • tcpdump excels at lightweight, scriptable packet capture on remote systems and embedded devices
  • Wireshark provides superior analysis capabilities with its graphical interface and protocol dissectors
  • Combining both tools creates a powerful workflow for comprehensive network analysis
  • Proper filtering reduces noise and improves performance in high-traffic environments
  • Security and legal considerations must guide all packet capture activities
  • Regular practice with real traffic patterns builds proficiency and pattern recognition

Recommended Learning Path

  1. Master basic capture and filtering
    • Practice tcpdump syntax daily
    • Build a personal filter library
    • Learn BPF syntax thoroughly
  2. Develop protocol expertise
    • Study TCP/IP fundamentals
    • Understand application protocols
    • Learn to identify anomalies
  3. Build analysis skills
    • Practice with sample captures
    • Participate in capture contests
    • Analyze your own network traffic
  4. Automate and scale
    • Create capture scripts
    • Build analysis pipelines
    • Integrate with monitoring systems

Additional Resources

  • Official Documentation
    • tcpdump man page: man tcpdump
    • Wireshark User Guide: wireshark.org/docs/
    • pcap-filter man page: man pcap-filter
  • Sample Captures
    • Wireshark Sample Captures: wiki.wireshark.org/SampleCaptures
    • PacketLife Capture Collection: packetlife.net/captures/
    • Netresec PCAP Files: netresec.com/index.ashx?page=PcapFiles
  • Community and Support
    • Wireshark Q&A: ask.wireshark.org
    • tcpdump-workers mailing list
    • Reddit r/networking and r/netsec

Appendices and Quick References

tcpdump Filter Cheat Sheet

Basic Filters

# Host filters
host 192.168.1.1              # To/from host
src host 10.0.0.1             # From host
dst host 10.0.0.2             # To host
not host 192.168.1.1          # Exclude host

# Network filters  
net 192.168.0.0/16            # Network range
src net 10.0.0.0/8            # Source network
dst net 172.16.0.0/12         # Destination network

# Port filters
port 80                        # Port 80 (src or dst)
src port 1234                  # Source port
dst port 80                    # Destination port
portrange 1-1024               # Port range
not port 22                    # Exclude port

# Protocol filters
tcp                            # TCP only
udp                            # UDP only
icmp                           # ICMP only
ip proto 47                    # GRE traffic
arp                           # ARP traffic

Advanced Filters

# TCP flags
'tcp[tcpflags] & (tcp-syn) != 0'                    # SYN flag set
'tcp[tcpflags] & (tcp-syn|tcp-ack) == tcp-syn'      # SYN only (no ACK)
'tcp[tcpflags] & (tcp-fin) != 0'                    # FIN flag set
'tcp[tcpflags] & (tcp-push) != 0'                   # PUSH flag set
'tcp[tcpflags] & (tcp-rst) != 0'                    # RST flag set

# Packet size
greater 1000                   # Packets larger than 1000 bytes
less 100                       # Packets smaller than 100 bytes

# Complex combinations
'host 192.168.1.1 and not (port 22 or port 443)'
'src net 10.0.0.0/8 and dst port 80'
'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'  # HTTP with data

Wireshark Display Filter Quick Reference

Common Display Filters

# IP filters
ip.addr == 192.168.1.1        # IP address (src or dst)
ip.src == 10.0.0.1            # Source IP
ip.dst == 10.0.0.2            # Destination IP
ip.addr == 192.168.1.0/24     # Subnet

# TCP/UDP filters
tcp.port == 80                 # TCP port
udp.port == 53                 # UDP port
tcp.stream eq 0                # TCP stream number
tcp.flags.syn == 1             # SYN flag set
tcp.flags.ack == 1             # ACK flag set

# Protocol filters
http                           # HTTP traffic
dns                           # DNS traffic
ssh                           # SSH traffic
ssl or tls                    # SSL/TLS traffic

# Analysis filters
tcp.analysis.retransmission    # Retransmitted packets
tcp.analysis.duplicate_ack     # Duplicate ACKs
tcp.analysis.zero_window       # Zero window
frame.time_delta > 1           # Time delta > 1 second

Useful Filter Combinations

# HTTP errors
http.response.code >= 400

# DNS queries (not responses)
dns.flags.response == 0

# Large packets
frame.len > 1500

# TCP problems
tcp.analysis.flags

# Non-standard ports
tcp.port != 80 and tcp.port != 443 and tcp.port != 22

# Specific TCP conversation
ip.addr==192.168.1.1 and ip.addr==192.168.1.2 and tcp.port==80

Sample Automation Scripts

Continuous Monitoring Script

#!/bin/bash
# continuous_monitor.sh - Monitor network and alert on anomalies

INTERFACE="eth0"
THRESHOLD_PPS=10000  # Packets per second threshold

monitor_traffic() {
    while true; do
        # Capture 1000 packets and analyze
        STATS=$(timeout 10 tcpdump -i $INTERFACE -nn -c 1000 2>&1)
        
        # Check for SYN flood
        SYN_COUNT=$(echo "$STATS" | grep -c "Flags \[S\]")
        if [ $SYN_COUNT -gt 500 ]; then
            echo "ALERT: Possible SYN flood detected! Count: $SYN_COUNT"
            logger -p local0.warning "SYN flood detected on $INTERFACE"
        fi
        
        # Check for port scan
        UNIQUE_PORTS=$(echo "$STATS" | awk '{print $5}' | cut -d. -f5 | sort -u | wc -l)
        if [ $UNIQUE_PORTS -gt 50 ]; then
            echo "ALERT: Possible port scan detected! Unique ports: $UNIQUE_PORTS"
            logger -p local0.warning "Port scan detected on $INTERFACE"
        fi
        
        sleep 30
    done
}

# Start monitoring
monitor_traffic

Traffic Report Generator

#!/bin/bash
# generate_report.sh - Generate traffic analysis report from pcap

PCAP_FILE=$1
REPORT_FILE="traffic_report_$(date +%Y%m%d_%H%M%S).html"

cat << EOF > $REPORT_FILE

Network Traffic Analysis Report

 

Generated: $(date)

 

File: $PCAP_FILE

 

Summary Statistics

 

$(capinfos $PCAP_FILE)

Protocol Distribution

$(tshark -r $PCAP_FILE -z io,phs -q)

Top Conversations

$(tshark -r $PCAP_FILE -z conv,ip -q | head -20)

HTTP Requests

$(tshark -r $PCAP_FILE -Y "http.request" -T fields -e frame.time -e ip.src -e http.host -e http.request.uri | head -50)

DNS Queries

$(tshark -r $PCAP_FILE -Y "dns.qry.name" -T fields -e frame.time -e ip.src -e dns.qry.name | head -50)

TCP Errors

$(tshark -r $PCAP_FILE -Y "tcp.analysis.flags" -T fields -e frame.time -e ip.src -e ip.dst -e tcp.analysis.flags | head -50)

 

EOF

echo “Report generated: $REPORT_FILE”

Common Port Reference

Port Protocol Service
20/21 TCP FTP
22 TCP SSH
23 TCP Telnet
25 TCP SMTP
53 TCP/UDP DNS
67/68 UDP DHCP
80 TCP HTTP
110 TCP POP3
143 TCP IMAP
161/162 UDP SNMP
443 TCP HTTPS
445 TCP SMB
514 UDP Syslog
587 TCP SMTP (submission)
993 TCP IMAPS
995 TCP POP3S
1433 TCP MS SQL
1521 TCP Oracle
3306 TCP MySQL
3389 TCP RDP
5432 TCP PostgreSQL
5060 TCP/UDP SIP
6379 TCP Redis
8080 TCP HTTP Alternate
8443 TCP HTTPS Alternate
27017 TCP MongoDB

 

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *