tcpdump – CLI Packet Capture, BPF Filters & Output Decoding

1. What Is tcpdump?

tcpdump is a command-line packet analyser for Unix/Linux/macOS systems that captures and inspects network traffic in real time. It uses the libpcap library to read packets directly from a network interface and applies BPF (Berkeley Packet Filter) expressions to select only the traffic you care about.

It is the standard tool for on-the-wire packet capture when a GUI tool like Wireshark is unavailable — on servers, network appliances, and embedded Linux systems. Captures can be saved to .pcap files and opened in Wireshark for graphical analysis later.

Use Case What tcpdump Reveals
Connectivity troubleshooting Is traffic actually leaving/arriving on the interface? Are ARP requests being answered? Is the TCP handshake completing?
Protocol verification Confirm DHCP DORA, DNS query/response, OSPF Hello packets, BGP keepalives are present and correct
Security analysis Detect port scans, ARP spoofing, unexpected outbound connections, cleartext credentials in HTTP/FTP/Telnet
Performance diagnosis Identify TCP retransmissions, duplicate ACKs, window size issues, high RTT — symptoms of network congestion
Configuration validation Verify ACL allow/deny behaviour, NAT translation, routing decisions by watching actual packet flow

Related pages: How DNS Works | DNS Record Types | DHCP How It Works | Common Port Numbers | show ip route | Troubleshooting Methodology | End-to-End Troubleshooting Lab

2. Installation and Interface Discovery

# ── Check if tcpdump is installed ─────────────────────────────────────────
which tcpdump          # Shows path if installed: /usr/sbin/tcpdump
tcpdump --version      # Shows version and libpcap version

# ── Install tcpdump ────────────────────────────────────────────────────────
# Debian / Ubuntu:
sudo apt install tcpdump

# RHEL / CentOS / Fedora:
sudo yum install tcpdump    # or: sudo dnf install tcpdump

# macOS (comes pre-installed; or via Homebrew):
brew install tcpdump

# ── List available interfaces ──────────────────────────────────────────────
sudo tcpdump -D
# or:
tcpdump --list-interfaces

# Sample output:
# 1.eth0 [Up, Running, Connected]
# 2.lo [Up, Running, Loopback]
# 3.wlan0 [Up, Running, Wireless]
# 4.any (Pseudo-device that captures on all interfaces)

# ── Capture on ALL interfaces simultaneously ───────────────────────────────
sudo tcpdump -i any

# ── Capture on specific interface ──────────────────────────────────────────
sudo tcpdump -i eth0
sudo tcpdump -i ens3     # Common on newer Ubuntu/RHEL naming
sudo tcpdump -i enp0s3   # VirtualBox default NIC naming
Why sudo? Packet capture requires raw socket access — a privileged kernel operation. Regular users cannot open raw sockets. On some Linux distributions, you can grant tcpdump capture capability without full root: sudo setcap cap_net_raw,cap_net_admin+eip $(which tcpdump) — then run without sudo. On macOS, members of the access_bpf group can capture without sudo.

3. BPF Filter Syntax — Complete Reference

BPF (Berkeley Packet Filter) expressions are evaluated in kernel space for maximum efficiency — packets that don't match are discarded before being passed to userspace, minimising CPU and memory impact.

Primitives — the building blocks

Primitive Example What It Matches
host host 192.168.1.5 Any packet where src OR dst IP = 192.168.1.5
src host src host 10.0.0.1 Packets sourced FROM 10.0.0.1 only
dst host dst host 10.0.0.2 Packets destined TO 10.0.0.2 only
net net 192.168.0.0/24 Any packet where src OR dst is in the subnet
src net src net 10.0.0.0/8 Traffic originating from within the 10.x.x.x range
port port 443 Any packet where src OR dst port = 443
src port src port 1234 Packets with source port 1234 (client ephemeral port)
dst port dst port 80 Packets destined to port 80 (inbound HTTP requests)
portrange portrange 8000-8080 Any packet with port in the range 8000–8080
tcp tcp All TCP packets
udp udp All UDP packets
icmp icmp All ICMP packets (ping, unreachable, redirect, etc.)
arp arp All ARP packets (request and reply)
ether host ether host aa:bb:cc:dd:ee:ff Packets with specific source or destination MAC address
broadcast ether broadcast Ethernet broadcast frames (FF:FF:FF:FF:FF:FF)
vlan vlan 10 802.1Q tagged frames for VLAN 10 (on trunk-capable interfaces)

Boolean Operators

# and / && -- both conditions must be true:
sudo tcpdump 'tcp and port 22 and host 10.0.0.5'
# Matches: TCP traffic on port 22 involving 10.0.0.5

# or / || -- either condition must be true:
sudo tcpdump 'port 80 or port 443'
# Matches: HTTP or HTTPS traffic

# not / ! -- negate a condition:
sudo tcpdump 'not arp'
# Matches: everything except ARP

# Grouping with parentheses (requires quotes on shell):
sudo tcpdump '(src net 192.168.1.0/24 or src net 10.0.0.0/8) and dst port 443'
# Matches: HTTPS traffic from either internal subnet

# src and dst (both directions between two specific hosts):
sudo tcpdump 'src host 10.0.0.1 and dst host 10.0.0.2'
# Note: 'host A and host B' catches A-to-B AND B-to-A
# 'src host A and dst host B' catches ONLY A-to-B direction

Common Protocol Filter Examples

Goal Filter Expression
All DNS traffic port 53
DNS queries only (UDP, outbound to server) udp and dst port 53
DHCP discovery/request udp and (port 67 or port 68)
All SSH traffic tcp and port 22
HTTPS only tcp and port 443
All traffic to/from a host except SSH host 10.0.0.5 and not port 22
ICMP ping to a specific host icmp and host 8.8.8.8
Traffic from subnet, not to port 22 src net 192.168.1.0/24 and not dst port 22
OSPF protocol packets proto ospf
BGP (TCP port 179) tcp and port 179

4. Essential Command-Line Options

Option Function Example Notes
-i Select capture interface -i eth0 Use -i any to capture all interfaces
-w Write packets to .pcap file -w capture.pcap No output to terminal while writing; use Ctrl+C to stop
-r Read packets from .pcap file -r capture.pcap Applies filters when reading; no root required for -r
-c Capture N packets then stop -c 100 Avoids runaway captures; combine with filters
-n Disable DNS resolution (show IPs, not hostnames) -n Speeds output; avoids misleading reverse-DNS results
-nn Disable DNS AND port name resolution -nn Shows port numbers (80) instead of names (http)
-v Verbose — show TTL, ToS, checksum -v One level; use -vv or -vvv for more detail
-vv Very verbose — show protocol options -vv Adds TCP options (MSS, timestamp, SACK), DHCP options
-vvv Maximum verbosity -vvv Full protocol field decoding
-X Show packet payload in hex + ASCII -X Use to see cleartext credentials, HTTP headers, DNS names
-XX Show hex+ASCII including Ethernet header -XX Adds Layer 2 header to -X output
-A Show packet payload in ASCII only -A Cleaner for reading HTTP headers and plaintext protocols
-e Print MAC addresses (Layer 2 headers) -e Useful for ARP/VLAN troubleshooting
-s Set snap length (bytes per packet to capture) -s 0 -s 0 = capture full packet. Default 96B misses payloads
-S Print absolute TCP sequence numbers -S Default shows relative numbers; -S shows raw values
-p Disable promiscuous mode -p Default: promiscuous (captures all frames, not just host's). -p restricts to traffic destined for this host
-D List available interfaces -D Identify interface names before capturing
-C File rotation by size (MB) -C 10 Creates new file every 10 MB: file0, file1, file2...
-G File rotation by time (seconds) -G 60 Creates new file every 60 seconds; combine with -w timestamp
-W Limit number of rotation files -W 10 Keeps only last 10 files (circular buffer)

5. Decoding tcpdump Output Line by Line

# Standard output line:
14:23:05.123456 IP 192.168.1.100.54321 > 8.8.8.8.53: UDP, length 29
^               ^  ^                   ^            ^  ^    ^
Timestamp       IP Src_IP.SrcPort      Dst_IP.DstPort Proto Payload_length

# TCP output (more fields):
14:23:10.456789 IP 192.168.1.100.54890 > 93.184.216.34.80: Flags [S], seq 3456789012, win 65535, length 0
                                                            ^          ^                ^          ^
                                                            TCP flags  Sequence number  Window     Data length

# Complete annotated example:
14:23:10.456789 IP 192.168.1.100.54890 > 93.184.216.34.80: Flags [S], seq 3456789012, win 65535, options [mss 1460], length 0
                ^^                                          ^^^^^^^^^^  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                IP = IPv4 packet                            Flags:      Remaining TCP header fields
                (IP6 for IPv6)                              [S]=SYN
                                                            [F]=FIN
                                                            [P]=PSH
                                                            [R]=RST
                                                            [.]=ACK
                                                            [S.]=SYN+ACK

TCP Flag Reference

Flag Code in Output TCP Flag Meaning Seen In
[S] SYN Initiates a TCP connection First packet of 3-way handshake
[S.] SYN-ACK Server accepts connection Second packet of handshake
[.] ACK Acknowledgement of received data Third packet of handshake; every data ACK
[P.] PSH-ACK Push data to application immediately Most data segments after handshake
[F.] FIN-ACK Graceful connection close TCP teardown (4-way)
[R] RST Abrupt reset/reject connection Port closed; connection refused; firewall drop
[R.] RST-ACK Reset with acknowledgement Immediate connection rejection

Reading the Hex+ASCII Output (-X flag)

# Command:
sudo tcpdump -nn -i eth0 -X -c 1 dst port 80

# Output with -X:
14:25:30.123456 IP 192.168.1.100.54321 > 93.184.216.34.80: Flags [P.], seq 1:78, length 77
        0x0000:  4500 0074 3f3f 4000 4006 xxxx c0a8 0164  E..t??@[email protected]
        0x0010:  5db8 d822 d431 0050 1234 5678 8765 4321  ]..".1.P.4Vx.eC!
        0x0020:  8018 00e5 xxxx 0000 0101 080a xxxx xxxx  ................
        0x0030:  0000 0000 4745 5420 2f20 4854 5450 2f31  ....GET / HTTP/1
        0x0040:  2e31 0d0a 486f 7374 3a20 6578 616d 706c  .1..Host: exampl
        0x0050:  652e 636f 6d0d 0a                        e.com..

# Left column:  byte offset in hex
# Middle:       raw hex bytes (each pair = 1 byte)
# Right column: ASCII representation (. = non-printable)
# You can read "GET / HTTP/1.1\r\nHost: example.com" in the ASCII column

6. Capture File Management

# ── Write to PCAP file ─────────────────────────────────────────────────────
sudo tcpdump -i eth0 -w capture.pcap
# Ctrl+C to stop. File is binary PCAP format -- not human readable.

# ── Write with timestamp in filename ───────────────────────────────────────
sudo tcpdump -i eth0 -w capture-%Y%m%d-%H%M%S.pcap

# ── Read a PCAP file ───────────────────────────────────────────────────────
tcpdump -r capture.pcap
# No sudo required for reading; applies full filter syntax
tcpdump -r capture.pcap 'tcp and port 443'   # filter on read

# ── Capture then apply different filters at read time ──────────────────────
# First: capture everything (broad net)
sudo tcpdump -i eth0 -s 0 -w full_capture.pcap

# Later: extract only DNS from the full capture
tcpdump -r full_capture.pcap 'port 53'

# ── Large capture file rotation ────────────────────────────────────────────
# Rotate by size (10 MB per file):
sudo tcpdump -i eth0 -w /tmp/cap-%H%M%S.pcap -C 10

# Rotate by time (60 seconds per file), keep last 10:
sudo tcpdump -i eth0 -w /tmp/cap-%H%M%S.pcap -G 60 -W 10

# ── Pipe directly to Wireshark on a remote system ─────────────────────────
# On the remote server (via SSH):
ssh user@server 'sudo tcpdump -i eth0 -s 0 -w - "port 80"' | wireshark -k -i -
# Wireshark opens on local machine, displaying live capture from remote server!

7. Filtering TCP Flags with BPF

You can filter on specific TCP flags using BPF bit-mask expressions. This is useful for isolating connection setup (SYN), resets (RST), and other specific events.

# BPF TCP flag syntax:
# tcp[13] = the TCP flags byte (byte 13 of the TCP header, zero-indexed)
# Flag bits: FIN=1, SYN=2, RST=4, PSH=8, ACK=16, URG=32

# Capture only TCP SYN packets (new connections):
sudo tcpdump -nn 'tcp[13] == 2'
# or equivalently:
sudo tcpdump -nn 'tcp[tcpflags] == tcp-syn'

# SYN + ACK (server response to SYN):
sudo tcpdump -nn 'tcp[13] == 18'   # SYN(2) + ACK(16) = 18

# Only RST packets (rejected or aborted connections):
sudo tcpdump -nn 'tcp[13] & 4 != 0'
# or:
sudo tcpdump -nn 'tcp[tcpflags] & tcp-rst != 0'

# Only FIN packets (graceful close):
sudo tcpdump -nn 'tcp[tcpflags] & tcp-fin != 0'

# Practical: watch for connection resets to a web server:
sudo tcpdump -nn -i eth0 'tcp[tcpflags] & tcp-rst != 0 and port 80'

8. Real Troubleshooting Scenarios

Scenario 1: Verify DNS Resolution

# Problem: host cannot resolve DNS names; check if DNS traffic is flowing
sudo tcpdump -nn -i eth0 -vv 'port 53'

# Expected output (query then response):
# 14:30:00 IP 192.168.1.100.54321 > 192.168.1.1.53: A? google.com. (28)
# 14:30:00 IP 192.168.1.1.53 > 192.168.1.100.54321: A google.com. [1au] 1/0/1 A 142.250.80.46 (56)
#
# Diagnosis:
# If you see query but NO response: DNS server not reachable / not responding
# If no query at all: application not sending DNS / routing issue
# 'A?' = Type A (IPv4) query; 'AAAA?' = Type AAAA (IPv6) query

Scenario 2: Watch the TCP Three-Way Handshake

# Problem: TCP connection to web server fails; confirm whether handshake completes
sudo tcpdump -nn -i eth0 'tcp and host 93.184.216.34 and port 80'

# Expected 3-way handshake:
# Client > Server: Flags [S]    (SYN)
# Server > Client: Flags [S.]   (SYN-ACK)
# Client > Server: Flags [.]    (ACK)
# Then data: Flags [P.] (PSH-ACK with HTTP request)

# Diagnosis:
# Only [S] and no [S.]: server unreachable / firewall dropping SYN
# [S] then [R] or [R.]: port closed on server
# [S.] received but connection hangs: ACK lost, routing issue back to client

Scenario 3: Capture DHCP DORA

# Problem: host not getting IP; watch DHCP exchange
sudo tcpdump -nn -i eth0 -vv 'udp and (port 67 or port 68)'

# Expected DHCP DORA sequence:
# Client (0.0.0.0:68) > Broadcast (255.255.255.255:67): DHCP Discover
# Server (192.168.1.1:67) > Broadcast (255.255.255.255:68): DHCP Offer
# Client > Broadcast: DHCP Request
# Server > Broadcast: DHCP ACK
#
# Diagnosis:
# Discover but no Offer: no DHCP server / DHCP snooping blocking
# Offer but no ACK:      address conflict / server issue

Scenario 4: Detect ARP Spoofing

# Watch ARP traffic; detect multiple MACs claiming same IP
sudo tcpdump -nn -e -i eth0 arp

# Sample output:
# 14:35:10 00:11:aa:bb:cc:dd > ff:ff:ff:ff:ff:ff ARP, Request who-has 192.168.1.1 tell 192.168.1.100
# 14:35:10 00:11:22:33:44:55 > ff:ff:ff:ff:ff:ff ARP, Request who-has 192.168.1.1 tell 192.168.1.100
#
# Red flag: same IP answered by two different MACs in short succession
# 14:35:11 00:aa:bb:cc:dd:ee > ff:ff:ff:ff:ff:ff ARP, Reply 192.168.1.1 is-at 00:aa:bb:cc:dd:ee
# 14:35:11 00:ff:ee:dd:cc:bb > ff:ff:ff:ff:ff:ff ARP, Reply 192.168.1.1 is-at 00:ff:ee:dd:cc:bb
# Two different MACs both claiming to be 192.168.1.1 = ARP spoofing attack!

Scenario 5: Monitor ICMP Connectivity

# Problem: ping to 8.8.8.8 fails; verify ICMP at wire level
sudo tcpdump -nn -i eth0 'icmp and host 8.8.8.8'

# Expected ping output:
# 14:40:00 IP 192.168.1.100 > 8.8.8.8: ICMP echo request, id 1234, seq 1, length 64
# 14:40:00 IP 8.8.8.8 > 192.168.1.100: ICMP echo reply,   id 1234, seq 1, length 64
#
# Diagnosis:
# Request but no reply: routing problem / firewall at 8.8.8.8 blocking ICMP
# No request seen:      local routing issue / default route missing
# ICMP unreachable received: router along path reports no route to destination

9. Advanced Filtering Techniques

# ── Capture specific subnet traffic excluding management ───────────────────
sudo tcpdump -nn -i eth0 'src net 192.168.0.0/16 and not dst port 22'

# ── Watch only new TCP connections (SYN only, no ACK) ──────────────────────
sudo tcpdump -nn 'tcp[tcpflags] == tcp-syn'

# ── Find all RST packets (connection resets -- sign of trouble) ────────────
sudo tcpdump -nn 'tcp[tcpflags] & tcp-rst != 0'

# ── Capture HTTP GET requests only ────────────────────────────────────────
# Match the ASCII 'GET' in the TCP payload:
sudo tcpdump -nn -A 'tcp dst port 80 and tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x47455420'
# 0x47455420 = 'GET ' in ASCII

# ── Capture packets larger than 1400 bytes (find large transfers) ──────────
sudo tcpdump 'greater 1400'

# ── Capture packets smaller than 64 bytes (runt frames) ───────────────────
sudo tcpdump 'less 64'

# ── IPv6 only ─────────────────────────────────────────────────────────────
sudo tcpdump -nn ip6

# ── Filter by ICMP type (type 8 = echo request / ping) ────────────────────
sudo tcpdump 'icmp[icmptype] == icmp-echo'

# ── Capture all traffic, dump to stdout, compress with gzip ───────────────
sudo tcpdump -i eth0 -s 0 -w - | gzip -c > /tmp/capture.pcap.gz

10. Integrating with Wireshark and Other Tools

# ── Convert/open .pcap in Wireshark ───────────────────────────────────────
# On local machine: just double-click the .pcap file (if Wireshark installed)
# On Linux GUI:
wireshark capture.pcap &

# ── Live remote capture in Wireshark via SSH ──────────────────────────────
ssh user@remote-server 'sudo tcpdump -U -i eth0 -s 0 -w - "port 80"' | wireshark -k -i -
# -U = unbuffered output (important for live streaming); -w - = write to stdout

# ── Pipe to tshark (CLI Wireshark) for analysis ───────────────────────────
sudo tcpdump -i eth0 -s 0 -w - | tshark -r - -T fields -e ip.src -e ip.dst -e tcp.dstport

# ── Use grep to find patterns in ASCII output ─────────────────────────────
sudo tcpdump -nn -A -i eth0 'port 80' | grep -i 'GET\|POST\|Host:'

# ── Count packets per source IP (basic traffic analysis) ──────────────────
sudo tcpdump -nn -i eth0 | awk '{print $3}' | cut -d. -f1-4 | sort | uniq -c | sort -rn | head

# ── Extract URLs from HTTP traffic ────────────────────────────────────────
sudo tcpdump -nn -A -i eth0 'port 80' | grep -oP '(?<=GET ).*(?= HTTP)'

11. Promiscuous Mode and Interface Modes

By default, tcpdump places the network interface into promiscuous mode — the NIC accepts ALL frames on the wire, not just those addressed to its own MAC. This allows capturing traffic between other hosts on the same segment (useful on hubs; ineffective on switched networks without a mirror/SPAN port).

  Promiscuous mode on a HUB (captures all traffic):
  Hub -- PC-A, PC-B, PC-C, tcpdump-host
  tcpdump sees all frames (PC-A to PC-B, PC-B to PC-C, etc.)

  Promiscuous mode on a SWITCH (limited):
  Switch forwards frames only to correct destination port.
  tcpdump on Port-4 only sees:
    - Traffic TO/FROM the tcpdump host
    - Broadcasts and unknown unicast floods
    - NOT traffic between PC-A and PC-B (different ports)

  Solution for full capture on a switch:
  - SPAN port (Switched Port Analyser / port mirroring):
    Switch(config)# monitor session 1 source interface Gi0/1 - 3
    Switch(config)# monitor session 1 destination interface Gi0/24
    Connect tcpdump host to Gi0/24 -- sees ALL traffic from Gi0/1-3

  - TAP device (hardware): physically intercepts the link; passive

12. Security, Legal, and Ethical Considerations

  • Authorisation is mandatory. Capturing traffic on a network you do not own or have explicit written permission to test is illegal in most jurisdictions (e.g., Computer Fraud and Abuse Act in the US, Computer Misuse Act in the UK). Always obtain written authorisation before capturing.
  • Sensitive data in captures. PCAP files may contain cleartext passwords (HTTP, FTP, Telnet, SNMPv1/v2), authentication tokens, session cookies, and private health or financial data. Handle .pcap files as sensitive data: encrypt at rest, restrict access, delete when no longer needed.
  • Performance impact. Promiscuous mode + no filter on a busy interface can consume significant CPU and disk. Always use specific BPF filters in production.
  • Log your captures. Document: interface, filter used, start/end time, purpose, and who authorised the capture. This protects you and creates an audit trail.
  • Privacy regulations. GDPR (EU), HIPAA (US healthcare), and other regulations may restrict capturing and storing user traffic even on your own network. Consult your organisation's data protection policy.

13. Hands-On Practice Command Reference

Task Command Goal
List interfaces sudo tcpdump -D Find the correct interface name
Capture all, 30 sec sudo timeout 30s tcpdump -i eth0 -nn Observe live packet flow without DNS resolution
Filter by source IP sudo tcpdump -nn -i eth0 src host 192.168.1.100 See only traffic originating from one host
Capture HTTP traffic sudo tcpdump -nn -A -i eth0 port 80 Read HTTP headers and content in ASCII
Save 100 packets sudo tcpdump -i eth0 -c 100 -s 0 -w sample.pcap Full-packet capture for Wireshark analysis
Read pcap with filter tcpdump -r sample.pcap 'port 53' Extract DNS traffic from saved capture
Verbose DNS watch sudo tcpdump -nn -vv -i eth0 port 53 See full DNS query/response details
Hex + ASCII payload sudo tcpdump -nn -X -i eth0 -c 5 port 80 Inspect HTTP payload in hex and ASCII
Watch ICMP only sudo tcpdump -nn -i eth0 icmp Debug ping failures; verify ICMP at wire level
SYN packets only sudo tcpdump -nn 'tcp[tcpflags]==tcp-syn' Watch new connection attempts
Rotating capture sudo tcpdump -i eth0 -s 0 -w /tmp/cap-%H%M%S.pcap -G 300 -W 12 5-minute rotating files, keep 12 (1 hour of history)
ICMP excluding host sudo tcpdump 'icmp and not host 10.1.1.1' Exclude noisy/known-good host from ICMP capture

14. Key Points & Exam Tips

  • Basic syntax: sudo tcpdump [options] [filter]. Requires root on most systems (sudo) for raw socket access.
  • -i selects interface (-i eth0, -i any). Use -D to list available interfaces.
  • -w writes PCAP file; -r reads PCAP file. No root needed for -r. Apply filters on both capture and read.
  • -c limits packet count. -n disables DNS resolution (faster, cleaner). -nn disables both DNS and port name resolution.
  • -X shows payload in hex + ASCII. -A shows ASCII only (cleaner for HTTP). -XX includes Ethernet header in hex output. -s 0 captures the full packet (default truncates).
  • BPF primitives: host, net, port, src, dst, tcp, udp, icmp, arp. Combine with and, or, not.
  • TCP flags in output: [S]=SYN (new connection), [S.]=SYN-ACK, [.]=ACK, [P.]=PSH-ACK (data), [F.]=FIN (close), [R]=RST (reset/reject).
  • File rotation: -C by size (MB); -G by time (seconds); -W limits file count (circular buffer). Use timestamp in filename: -w cap-%H%M%S.pcap.
  • On switched networks, tcpdump only sees traffic to/from the capture host plus broadcasts. Use a SPAN/mirror port on a managed switch to capture traffic between other hosts.
  • Always use filters in production to minimise CPU load and capture size. Always have authorisation before capturing — packet capture without permission is illegal.

Related pages: How DNS Works | DNS Record Types | DHCP How It Works | Common Port Numbers | show ip route | Troubleshooting Methodology | End-to-End Troubleshooting Lab

15. tcpdump – CLI Packet Capture Quiz

1. A network engineer notices a host cannot reach its default gateway. They run tcpdump on the host to investigate. What command captures ARP traffic to watch whether the gateway MAC is being resolved, and also shows the MAC addresses in the output?

Correct answer is D. To troubleshoot a host that cannot reach its gateway, ARP resolution is the first thing to verify — the host must ARP for the gateway's MAC before it can send any IP packets. The command sudo tcpdump -nn -e -i eth0 arp does exactly what is needed: "arp" is the BPF filter that captures only ARP frames (both requests and replies). "-e" adds the Ethernet header fields to each output line, showing the source and destination MAC addresses — critical for seeing ARP responses and confirming the gateway is responding. "-nn" disables DNS and port name resolution for cleaner, faster output. Expected output if working: "ARP, Request who-has 192.168.1.1 tell 192.168.1.100" followed by "ARP, Reply 192.168.1.1 is-at aa:bb:cc:dd:ee:ff". If no reply appears, the gateway MAC is not being resolved — either the gateway is down, unreachable, or ARP is being blocked. Option A (port 53) captures DNS, not ARP. Option B (-X icmp) captures ICMP payload which is only useful once ARP is working. Option C incorrectly uses -r (read file) for what should be live capture.

2. An engineer needs to capture all traffic on a busy production server for exactly 5 minutes, saving the full packets to a file for later analysis in Wireshark — without any real-time terminal output. What command achieves this?

Correct answer is B. Breaking down each element: timeout 300 is a Unix utility that runs a command for a maximum of 300 seconds (5 minutes) then sends SIGTERM to stop it. This is the correct way to time-limit a tcpdump session. -s 0 sets the snap length to zero, which means "capture the entire packet." Without this, tcpdump defaults to a limited snap length (often 96 bytes on older versions or 65535 on newer) which may truncate payloads — Wireshark analysis would be incomplete. -w capture.pcap writes in binary PCAP format with no terminal output (all packets go to file, nothing to screen). This is exactly what the engineer needs — a clean, full-packet capture file for Wireshark. Option A incorrectly uses -X (hex output flag) where -w should go. Option C uses -c 300 which limits to 300 packets, not 300 seconds — on a busy server this could stop in milliseconds. Option D uses -r (read file) incorrectly; -r reads a file, it doesn't write one.

3. A tcpdump output shows the following line. What does it mean?
14:52:10.123 IP 10.0.0.5.45123 > 192.168.1.10.80: Flags [R.], seq 0, ack 1, win 0, length 0

Correct answer is C. Parsing the output line: "14:52:10.123" = timestamp. "IP" = IPv4 packet. "10.0.0.5.45123" = source IP 10.0.0.5, source port 45123 (client ephemeral port). ">" = direction of traffic (from source to destination). "192.168.1.10.80" = destination IP 192.168.1.10, destination port 80 (HTTP). "Flags [R.]" = RST + ACK flags set simultaneously. "seq 0, ack 1, win 0, length 0" = no data payload, window size 0, sequence number 0. The [R.] (RST-ACK) flag combination means the destination is immediately rejecting and terminating a TCP connection. This is the server's (192.168.1.10) response back to the client (10.0.0.5) — wait, the direction shows the packet is FROM 10.0.0.5 TO 192.168.1.10, so this RST is being sent by 10.0.0.5 toward port 80 on 192.168.1.10. This means 10.0.0.5 received something unexpected (possibly a SYN-ACK for a connection it no longer has) and is resetting it. In practice, RST packets indicate: port closed, connection refused, firewall reset, or a stale connection being terminated.

4. An engineer wants to capture a long-running session on a production server, rotating the capture file every 10 minutes and keeping only the last 6 files (1 hour of history). What command achieves this?

Correct answer is A. Understanding the rotation flags: -G seconds = rotate to a new file every N seconds. 600 seconds = 10 minutes. -W count = keep only the last N files. When the Nth+1 file would be created, tcpdump overwrites the oldest, acting as a circular buffer. 6 files × 10 minutes each = 60 minutes (1 hour) of retained capture. %H%M in the filename uses strftime format to embed the hour and minute — each file gets a unique timestamp name like cap-1430.pcap, cap-1440.pcap, etc. This is the standard approach for long-running production captures where you want recent history but don't want to fill the disk. Option B uses -c 600 (600 packets, not time-based). Option C uses -C 10 which rotates by file SIZE (10 MB), not by time — not what the engineer asked for. Option D incorrectly uses -r (read file) instead of -w. Note: -G requires -w to specify the output filename pattern.

5. A security analyst needs to capture HTTPS traffic (port 443) from a specific server (10.10.10.50) but exclude traffic from the monitoring system itself (10.10.10.200). What is the correct BPF filter?

Correct answer is C. Building the BPF filter logically: Requirement 1 — HTTPS traffic: port 443. Requirement 2 — involving the specific server: host 10.10.10.50 (matches either src or dst). Requirement 3 — exclude the monitoring system: not host 10.10.10.200 (exclude any packet where src or dst is the monitoring IP). Combine with AND: 'port 443 and host 10.10.10.50 and not host 10.10.10.200'. This captures: port 443 packets involving 10.10.10.50, but none involving 10.10.10.200. Single quotes are required on the shell because the expression contains spaces. Option A has incorrect syntax (missing 'and' before 'not'). Option B would include 10.10.10.200 traffic (AND means it must be present, not excluded). Option D would capture way too much — all port 443 traffic OR anything not from 10.10.10.200, which is nearly everything.

6. A tcpdump capture shows only the first few lines of an HTTP request but the payload is cut off with "..." after 96 bytes. The engineer needs to see the complete HTTP response body. What was missing from the original capture command and how is it fixed?

Correct answer is B. The -s option controls the "snap length" — the maximum number of bytes captured per packet. On older versions of tcpdump, the default snap length was 68 or 96 bytes, capturing only the headers of most packets and truncating the payload. On newer versions the default is often 65535 bytes, but you should always specify -s 0 explicitly to guarantee full-packet capture. Setting -s 0 means "no limit — capture the complete packet." For an HTTP response body, the payload can be many kilobytes. Without -s 0, you see the TCP and HTTP headers (usually under 100 bytes) but the response body is truncated. Fix: re-run with -s 0: sudo tcpdump -nn -A -s 0 -i eth0 port 80. The -A flag (ASCII output) combined with -s 0 shows the complete HTTP response body in readable text. Note: larger snap lengths mean larger .pcap files — on high-traffic links, -s 0 can generate gigabytes quickly. Use a specific filter alongside it.

7. An engineer runs sudo tcpdump -nn -i eth0 'tcp[tcpflags]==tcp-syn' on a web server and sees hundreds of SYN packets per second from random source IPs but no corresponding SYN-ACK responses. What does this indicate?

Correct answer is D. The filter tcp[tcpflags]==tcp-syn captures ONLY TCP SYN packets — the first packet of the three-way handshake used to initiate new TCP connections. Normal web traffic shows SYN followed by SYN-ACK followed by ACK — a complete handshake. What the engineer sees: hundreds of SYN packets per second from diverse/random source IPs with no SYN-ACK completions. This is the signature of a SYN flood attack: an attacker (or botnet) sends massive numbers of TCP SYN packets to the server, often with spoofed source IPs. For each SYN, the server allocates a half-open connection entry and sends a SYN-ACK. Since the source IPs are spoofed, no ACK ever arrives. The server's half-open connection table fills up, refusing new legitimate connections. Mitigation: SYN cookies (allows server to respond without state until ACK arrives), rate limiting with iptables/nftables, or upstream scrubbing service. The tcpdump output is invaluable for quickly confirming a SYN flood vs normal traffic spike.

8. An engineer captures traffic on a core switch port but only sees traffic to and from the capture host, not between other hosts on the network. They expected to see all inter-host traffic. What is the reason, and what change is needed?

Correct answer is A. This is the fundamental limitation of packet capture on switched networks. Promiscuous mode (used by tcpdump by default) puts the NIC in a state where it accepts ALL frames received by the NIC — not just those addressed to its own MAC. On a HUB, all traffic physically reaches every port, so promiscuous mode gives full visibility. On a SWITCH, traffic is forwarded ONLY to the correct destination port. The capture host's NIC physically never receives frames destined for other hosts — the switch doesn't send them to it. Therefore, tcpdump can only see: (1) traffic addressed to or from the capture host, and (2) broadcast and unknown unicast floods. Adding -p (option B) DISABLES promiscuous mode, making the situation WORSE. The correct solution is to configure a SPAN (Switched Port Analyser) or port mirror session on the managed switch, which copies all traffic from the monitored source ports to the designated mirror destination port where the capture host is connected. Alternatively, a physical TAP device on the link passively copies all traffic without switch configuration.

9. A developer captures HTTP traffic with tcpdump and plans to share the .pcap file with a colleague. The capture was taken on a corporate network with multiple users. What concern should they address before sharing the file?

Correct answer is C. This question tests the ethical and legal dimension of packet capture — critical knowledge for any network professional. HTTP (port 80) is unencrypted. A capture of HTTP traffic on a corporate network can contain: usernames and passwords submitted via web forms, session cookies (which can be used to hijack sessions), personal data from web application interactions, browsing history and URLs of every user whose traffic was captured, potentially healthcare, financial, or other regulated data. Before sharing the .pcap file: (1) Confirm authorisation — was this capture approved and is the recipient authorised to see this data? (2) Check privacy regulations — GDPR requires explicit purpose limitation; HIPAA protects health information. (3) Sanitise if needed — tools like TraceWrangler can anonymise IP addresses and remove payload data from .pcap files. (4) Secure transmission — encrypt the file and use secure transfer methods. The .pcap format (option A) is universally compatible (libpcap format used by both tcpdump and Wireshark). Non-root users can open .pcap files — capturing requires root, but reading does not.

10. An engineer needs to run a live tcpdump on a remote Linux server and view the results in Wireshark on their local laptop — without first saving a file to the server. What command achieves this?

Correct answer is B. This is an elegant and powerful technique used by network engineers who need Wireshark's analysis capabilities on traffic from remote servers. The command works as a pipeline: ssh user@server establishes an SSH connection. 'sudo tcpdump -U -i eth0 -s 0 -w - "port 80"' runs on the remote server: -w - writes raw PCAP data to standard output (stdout) rather than a file; -U enables per-packet buffering so each captured packet is immediately flushed to stdout without waiting for the buffer to fill (critical for real-time streaming). The | (pipe) sends this raw PCAP stream through the SSH tunnel to the local machine. wireshark -k -i - opens Wireshark: -k starts capturing immediately; -i - reads from standard input (the piped PCAP stream). Wireshark displays packets in real time as if it were connected to the remote interface directly. This is fully encrypted (all traffic goes through SSH) and requires no intermediate file storage on the server. Option A saves a file first (the question specifically says "without saving a file"). Options C and D work but are more complex or require additional software installation.

← Back to Home