How do you write tcpdump filters, and how do you read a tcpdump line?
Show the answer
Say this first
tcpdump takes a BPF filter in pcap-filter syntax: primitives like host, net, port, portrange, with
src or dst qualifiers and protocol names (tcp, udp, icmp, arp), joined with and, or, not
and parentheses. I always use -nn so it does not resolve names or ports, -i for the interface, -c to
stop after a count, and -w to save a pcap for Wireshark. Quote the filter.
Go deeper
Filters I actually use
tcpdump -i ens192 -nn host 10.0.10.30
tcpdump -i ens192 -nn 'src net 10.20.0.0/24 and dst port 443'
tcpdump -i any -nn 'port 53'
tcpdump -i ens192 -nn -e arp
tcpdump -i ens192 -nn 'icmp or tcp[tcpflags] & (tcp-syn|tcp-rst) != 0'
tcpdump -i ens192 -nn 'tcp port 22 and not host 10.0.50.10'
tcpdump -i ens192 -nn -c 2000 -w /tmp/web.pcap 'host 198.51.100.80 and port 443'
tcpdump -nn -r /tmp/web.pcap 'tcp[tcpflags] & tcp-rst != 0'Reading a handshake
09:21:14.502113 IP 10.0.10.21.51544 > 198.51.100.80.443: Flags [S], seq 3125110123, win 64240, options [mss 1460,sackOK,TS val 1840233 ecr 0,nop,wscale 7], length 0
09:21:14.505391 IP 198.51.100.80.443 > 10.0.10.21.51544: Flags [S.], seq 2287712361, ack 3125110124, win 65160, options [mss 1460,sackOK,TS val 99120 ecr 1840233,nop,wscale 7], length 0
09:21:14.505430 IP 10.0.10.21.51544 > 198.51.100.80.443: Flags [.], ack 1, win 502, length 0- Address and port are joined with a dot:
10.0.10.21.51544. - Flags:
SSYN,S.SYN-ACK,.ACK,P.data with push,F.FIN,Rreset. - After the handshake tcpdump prints relative sequence numbers (
ack 1);-Sshows absolute ones. win 502is scaled: with wscale 7 that is 502 x 128 bytes.- The 3.3 ms between SYN and SYN-ACK is the network round trip to the server.
Options
-e link-layer header (MACs, VLAN tag), -v more IP detail, -A payload as ASCII, -X hex,
-Q in or -Q out for direction, -s snap length (the modern default captures whole packets).
They will ask next
Why do you always use -nn?
Without it tcpdump does reverse DNS for every address, which is slow, can hide output while it waits, and adds its own DNS packets to the capture.
How do you capture only one VLAN on a trunk?
tcpdump -i ens192 -nn -e 'vlan 10 and host 10.10.0.21'. Putvlanfirst: it shifts the header offsets for every primitive after it, sohost x and vlan 10does not mean the same thing.What does -i any change?
It captures on every interface using Linux cooked capture, so you lose the real Ethernet header and the interface is not put in promiscuous mode. Good for "which interface does this leave on", bad for MAC-level work.
Traps
- Forgetting quotes, so the shell eats the parentheses or
&. - Writing
port 53and thinking it only matches UDP. It matches TCP too; addudpif you mean it.