Packet Capture with tcpdump
tcpdump capture syntax, BPF filters, writing pcap files, and tshark for terminal analysis.
Overview
Overview tcpdump is the essential command-line packet capture tool. It uses libpcap and BPF (Berkeley Packet Filter) to capture and filter network packets at the kernel level, minimizing the data sent to userspace.
Basic usage: tcpdump -i eth0 captures on eth0. tcpdump -i any captures on all interfaces (useful when you're not sure which interface traffic uses, but misses some VLAN information). tcpdump with no filter prints all packets — typically too much data.
BPF filter expressions: The filter language is concise and powerful. Primitives: host 1.2.3.4 (source or destination), src host 1.2.3.4 (source only), dst host, port 80 (source or destination port), src port, dst port, tcp (TCP only), udp, net 10.0.0.0/8 (network). Combinations: and (&&), or (||), not (!). Parentheses for grouping: 'tcp and (port 80 or port 443)'.
Key flags: - -n: no DNS resolution (essential on busy servers) - -nn: no DNS and no service name resolution - -v/-vv/-vvv: increasing verbosity (protocol details) - -s 0: full packet capture (default in modern tcpdump is already 262144 bytes) - -e: include ethernet header (MAC addresses) - -A: print packet data as ASCII - -X: print as hex + ASCII - -w file.pcap: write raw packets to file (for Wireshark analysis) - -r file.pcap: read from file - -c N: stop after N packets
tshark: Terminal-based Wireshark. tshark -r file.pcap for reading captures, -Y 'display filter' for Wireshark display filters (more expressive than BPF), -T fields -e field for extracting specific fields.
Key concepts
- BPF filter syntax
- -i any capture
- snaplen with -s
- -w/-r for pcap files
Interview questions
- Write a tcpdump command to capture all HTTP traffic to/from port 80, excluding your SSH session, and save to a file.
- How would you capture and analyze a TLS handshake to debug a certificate issue?
Sign up free to read the full topic
More Linux topics
Start free on Cariara · Coding problems · System design studio