tcpdump Packet Capture Guide: BPF Filters and Troubleshooting - 夜莺博客

tcpdump Packet Capture Guide: BPF Filters and Troubleshooting

When a server "can't reach the network," the fastest way to separate fact from guesswork is a packet capture — and tcpdump is the tool that works everywhere, from a production server to an embedded Linux appliance. The key to using it well is the BPF filter: tcpdump compiles your expression to kernel bytecode so only the packets you care about are copied to userspace. This guide covers interface selection, the BPF primitives that matter, reading TCP flags, and the practical troubleshooting scenarios where tcpdump shines.

Installation and Interface Discovery

# Debian/Ubuntu
sudo apt install tcpdump
# RHEL/CentOS/Fedora
sudo yum install tcpdump
# List capture interfaces
sudo tcpdump -D
# Capture on all interfaces
sudo tcpdump -i any

BPF Filter Primitives

BPF expressions are evaluated in the kernel — packets that do not match are discarded before reaching userspace, minimizing CPU and memory impact.

host 192.168.1.5            # src OR dst = 192.168.1.5
src host 10.0.0.1           # source only
dst host 10.0.0.2           # destination only
net 192.168.1.0/24          # subnet
port 443                    # either direction
src port 443 and dst host 10.0.0.5
vlan 10                     # 802.1Q tagged frames for VLAN 10
ether host aa:bb:cc:dd:ee:ff  # specific MAC
tcp and port 22             # boolean combination
not port 22

Reading TCP Flags

Flag letters in output: [S] SYN, [S.] SYN-ACK, [.] bare ACK, [P.] PSH-ACK (data), [F.] FIN, [R] RST. A burst of [S] with no [S.] means the remote side is not responding; an immediate [R] after [S] means the port is closed or a firewall is rejecting.

# SYN packets only (SYN flood detection)
sudo tcpdump -i eth0 'tcp[tcpflags] == tcp-syn'
# RST packets (connection resets)
sudo tcpdump -i eth0 'tcp[tcpflags] & tcp-rst != 0'

Practical Scenarios

# DNS queries and responses
sudo tcpdump -i any port 53
# ARP debugging (IP conflicts, resolution failures)
sudo tcpdump -nn -i enp3s0 arp
# Jumbo frames / MTU issues
sudo tcpdump -nn -i enp3s0 'greater 1500'
# Rolling capture for Wireshark
sudo tcpdump -nn -i enp3s0 -w /tmp/cap-%Y%m%d-%H%M%S.pcap -G 3600 -W 10 tcp port 80

Always add -nn to skip DNS and port-name resolution (much faster output), and use -w to save captures for Wireshark analysis. Pair tcpdump with Linux 网络故障排查方法 and Linux 运维高阶命令实战 for a complete Linux network troubleshooting toolkit.

原文链接:https://netstuts.com/tcpdump