Unit

Tcpdump Command: Packet Capture and Analysis

Learn tcpdump syntax, interfaces, BPF filters, TCP and DNS troubleshooting, pcap files, payload inspection, and safe long-running packet captures.

tcpdump is a command-line utility for capturing and displaying network packets. It is useful when a graphical analyzer is unavailable, when a quick diagnosis is needed, or when you want to collect a focused packet capture for later analysis.

This lesson covers interface selection, capture options, Berkeley Packet Filter (BPF) expressions, protocol troubleshooting, TCP interpretation, pcap files, payload output, and operational safety. It assumes basic shell usage and familiarity with IP addresses, subnets, ports, TCP, and UDP. For background, review computer networking, TCP and UDP ports, and IP routing.

What tcpdump does

tcpdump observes packets that pass through a selected network interface. An interface is a connection point such as eth0, ens33, wlan0, lo, or a virtual adapter. tcpdump can print packet summaries immediately or write captured packets to a pcap file.

  • Diagnose connectivity and routing problems.
  • Verify that an application sends and receives traffic.
  • Investigate DNS requests and responses.
  • Inspect DHCP and ARP exchanges.
  • Observe TCP connection establishment, resets, retransmissions, and teardown.
  • Collect evidence for later review in Wireshark or another packet analyzer.

tcpdump uses libpcap on many Unix-like systems. libpcap supplies packet-capture access and compiles BPF expressions into an efficient capture filter. A capture filter determines which packets are retained while capture is occurring, reducing processing and storage.

Permissions and safe packet capture

Capturing packets commonly requires root privileges because packet capture accesses a low-level interface and may expose traffic belonging to other processes or users. A typical command therefore begins with sudo:

sudo tcpdump -i eth0 -nn

Some operating systems support assigning a narrowly scoped capture capability or access to a capture group instead of granting full administrative access. Prefer the least privilege supported by your platform. Do not give a general user unrestricted administrative access merely to run tcpdump.

Only capture traffic when you have authorization. Packet data can contain passwords, cookies, session tokens, personal information, internal addresses, file contents, and confidential application data. Treat a pcap file as sensitive evidence:

  • Define the authorized host, service, interface, and time window before capturing.
  • Use the narrowest practical filter and snapshot length.
  • Store files with restrictive permissions and approved retention.
  • Do not email or upload captures to unapproved locations.
  • Remove or securely destroy captures when policy permits.

Encryption protects payloads in transit but does not make a capture harmless. Metadata such as addresses, ports, timing, DNS names, and packet sizes may still reveal sensitive information.

Selecting a network interface

First list interfaces visible to tcpdump:

tcpdump -D

The output normally includes a number and a device name. Use the device name with -i:

sudo tcpdump -i eth0 -nn

Choose the interface that actually carries the traffic under investigation:

  • lo is loopback traffic between processes on the same host.
  • Ethernet interfaces may be named eth0, enp1s0, or ens33.
  • Wi-Fi interfaces often have names such as wlan0 or wlp2s0.
  • Virtual, bridge, tunnel, VPN, and container interfaces may carry traffic that is not visible on the physical device in the form you expect.
  • The interface on a host running containers may be a bridge, a veth device, or a namespace-local interface.

The special any interface, where supported, can observe traffic from multiple interfaces:

sudo tcpdump -i any -nn

any is convenient for discovery, but it has limitations. Link-layer headers may not represent one physical interface, packets may appear differently from a device-specific capture, and it can make direction or duplicate analysis harder. For a precise investigation, identify the responsible interface and capture there. Also remember that a capture point sees only traffic that reaches that point; capturing on a workstation will not reveal packets exchanged entirely elsewhere.

Basic capture controls

Run tcpdump without a packet count for a continuing capture. Stop it with Ctrl+C. At the end, tcpdump usually reports how many packets were captured, received by the filter, and dropped by the kernel.

sudo tcpdump -i eth0 -nn

Use -c to stop automatically after a fixed number of packets:

sudo tcpdump -i eth0 -nn -c 50 host 192.0.2.25

Common controls include:

OptionPurposeTypical useCaution
-DList capture interfacesDiscover available devicesThe listed names and numbering vary by system.
-iSelect an interface-i eth0The wrong interface produces misleading or empty results.
-nDisable address name resolutionShow numeric IP addressesService names may still be displayed.
-nnDisable address and port name resolutionShow numeric addresses and portsOutput is less descriptive but more predictable and faster.
-vIncrease decoding detailInspect additional header fieldsMore output can make patterns harder to see.
-vvIncrease detail furtherDetailed protocol troubleshootingVerbose decoding increases terminal and processing load.
-cLimit packet countCollect a bounded sampleThe count applies to packets accepted by the capture filter.
-sSet snapshot lengthRetain only needed bytes per packetA short value may omit payload or fields needed later.
-pDisable promiscuous modeCapture only frames addressed to the host where supportedYou may miss other visible frames on a shared segment.
-lLine-buffer standard outputPipe live output to another commandText pipelines can still alter timing or consume resources.
-wWrite binary packets to a pcap fileSave evidence for later analysisIt does not produce human-readable terminal output.
-rRead a saved captureReview a pcap without live captureReading a file does not capture new traffic.
-APrint packet payload as ASCIIInspect authorized unencrypted test trafficIt can expose secrets and can be difficult to read.
-XPrint hex and ASCII payload dataInspect binary or mixed contentOutput becomes large; encrypted payload remains unintelligible.
-CRotate a file after a size threshold in megabytes-C 100 for approximately 100 MB filesUse with a file-count limit to prevent disk exhaustion.
-GRotate output after a time interval in secondsStart a new file periodicallyFilename handling and rotation behavior depend on the output template and platform.
-WLimit the number of rotated filesKeep a fixed capture set with rotationWhen the limit is reached, files may be overwritten or rotation may stop depending on the combination and implementation.

Promiscuous mode permits an interface to accept frames visible on the local network segment, rather than only frames addressed to the local host. It does not magically expose traffic that never reaches the interface, and switched networks normally limit what a host can see. Use -p when non-promiscuous capture is sufficient.

Use -l when live text must flow to another process:

sudo tcpdump -i eth0 -nn -l 'tcp port 443' | tee connection.log

For a bounded amount of packet data, combine -c with a suitable snapshot length. A smaller snapshot can reduce storage, but do not shorten it before confirming that the headers or payload needed for the investigation are retained.

Reading tcpdump output

A TCP line commonly contains a timestamp, source endpoint, destination endpoint, protocol, flags, sequence and acknowledgment information, window details, and packet length. For example, a line might conceptually look like this:

12:04:10.123456 192.0.2.25.49152 > 198.51.100.20.443: Flags [S], seq 1000, win 64240, length 0
  • The timestamp shows when the packet was observed by the capture point.
  • The source endpoint is the sender address and source port.
  • The > symbol points toward the destination endpoint.
  • The destination endpoint contains the receiving address and port.
  • Flags [S] identifies a TCP SYN.
  • seq is a TCP sequence number; it identifies the position of data in the byte stream.
  • length is the captured protocol payload length reported by tcpdump, not necessarily the total Ethernet frame size.

With -nn, an address and port remain numeric, making direction clear and avoiding delays from hostname or service-name lookups. A client ephemeral port usually appears on the source side, while a server's listening port appears on the destination side for an outbound request.

How protocols appear

  • TCP: Lines show flags such as SYN, ACK, FIN, and RST, along with sequence information and window values.
  • UDP: Lines show endpoints and a datagram length, but no handshake or acknowledgment mechanism.
  • ICMP: Lines identify messages such as echo requests, echo replies, and unreachable errors.
  • ARP: Lines describe IPv4-to-MAC address requests and replies on the local link.
  • DNS: tcpdump may decode query names, record types, response flags, and answers when the packet is visible and the decoder recognizes it.
  • DHCP: Broadcast UDP exchanges may show client and server messages while a host obtains configuration. DHCP commonly uses UDP ports 67 and 68.
  • IPv6: Use ip6 filters; output may show IPv6 addresses, extension headers, ICMPv6, and TCP or UDP carried inside IPv6.

Berkeley Packet Filter expressions

A BPF expression selects packets during capture. The basic building blocks are protocol names, addresses, networks, ports, qualifiers, and logical operators. Quote expressions containing spaces, parentheses, or shell-sensitive characters.

Filter patternWhat it selectsExample use case
host 192.0.2.25Packets to or from one hostFocus on one client or server
src host 192.0.2.25Packets whose source is the hostSee requests leaving a client
dst host 192.0.2.25Packets whose destination is the hostSee traffic arriving at a server
net 192.0.2.0/24Traffic to or from a networkInspect one subnet
port 443Traffic with source or destination port 443Inspect HTTPS connections
portrange 8000-8100Traffic using ports in a rangeObserve a service cluster or test range
tcpTCP packetsAnalyze connection behavior
udpUDP packetsInspect DNS, DHCP, or other datagrams
icmpIPv4 ICMP packetsInvestigate ping and error messages
arpARP packetsInvestigate local IPv4 address resolution
ipIPv4 packetsExclude non-IPv4 traffic
ip6IPv6 packetsInvestigate IPv6 connectivity
andRequires both expressionstcp and port 443
orRequires either expressionport 53 or port 67
notExcludes an expressiontcp and not port 22

Examples:

sudo tcpdump -i eth0 -nn 'tcp port 443'
sudo tcpdump -i eth0 -nn 'host 192.0.2.25 and tcp port 443'
sudo tcpdump -i eth0 -nn 'udp port 53 or tcp port 53'
sudo tcpdump -i eth0 -nn arp

Use parentheses to group logic. Quote them so the shell does not interpret them:

sudo tcpdump -i eth0 -nn '((src host 192.0.2.25 and dst port 443) or (dst host 192.0.2.25 and src port 443))'

This expression isolates a bidirectional conversation involving one host and port 443. In many cases, host 192.0.2.25 and tcp port 443 is enough and is easier to maintain.

Protocol-focused captures

HTTP and HTTPS

To observe HTTP connection behavior on port 80:

sudo tcpdump -i eth0 -nn 'tcp port 80'

To observe HTTPS transport connections:

sudo tcpdump -i eth0 -nn 'tcp port 443'

A normal capture can show addresses, ports, timing, TCP flags, packet sizes, retransmissions, and often TLS negotiation metadata. It generally cannot show the readable HTTP request or response body inside HTTPS because the application payload is encrypted. A TCP port number alone also does not prove which application is using that port.

DNS

DNS commonly uses UDP port 53 and can use TCP port 53 for larger responses, retries, or zone transfers. Capture both:

sudo tcpdump -i eth0 -nn 'udp port 53 or tcp port 53'

Compare the client query with the resolver response. A query without a response suggests a reachability, firewall, routing, or resolver availability problem. A negative DNS response proves that the resolver answered, so investigate the name, zone data, search domain, or client configuration. An unexpected resolver address may reveal a configuration or path issue.

DHCP

DHCP uses broadcast exchanges while a client is acquiring an IPv4 configuration. A focused capture can use:

sudo tcpdump -i eth0 -nn 'udp port 67 or udp port 68'

Because DHCP is broadcast-oriented and occurs before normal IP configuration, capture on the client-facing interface or the appropriate bridge, VLAN, relay, or access point. A capture on the wrong side of a relay may not show the original broadcast form.

ICMP

sudo tcpdump -i eth0 -nn icmp

Look for echo requests, echo replies, and messages such as destination unreachable or time exceeded. ICMP evidence can indicate reachability or path-related errors, but the absence of an echo reply does not by itself prove that all traffic is blocked; firewalls may filter ping while allowing a service.

ARP

sudo tcpdump -i eth0 -nn arp

An ARP request asks which device owns an IPv4 address; an ARP reply supplies a MAC address. Repeated requests without replies suggest an address, VLAN, switch, gateway, layer-2, or local-link problem. An ARP reply followed by failed TCP or ICMP traffic shifts attention toward routing, filtering, or the destination service.

TCP analysis fundamentals

For a service on TCP port 443, begin with a narrow filter:

sudo tcpdump -i eth0 -nn 'host 192.0.2.25 and tcp port 443'
Flag or patternMeaningTroubleshooting implication
SYNRequests a new TCP connectionShows that a client or peer is attempting to connect.
SYN-ACKOffers the connection and acknowledges the SYNShows that the destination or an intermediary responded.
ACKAcknowledges received sequence spaceThe three-way handshake completes when the client acknowledges the SYN-ACK.
FINGraceful close requestIndicates orderly connection teardown, usually in one direction at a time.
RSTImmediate resetOften indicates rejection, no listener, or an abrupt termination.
Repeated SYNThe connection attempt is sent againMay indicate no response, packet loss, filtering, or an unreachable destination.
RetransmissionA segment is sent again after expected acknowledgment was not observedInvestigate loss, congestion, asymmetric capture, or receiver and path problems.
Duplicate ACKAn acknowledgment repeats an earlier sequence valueCan indicate an out-of-order or missing segment and may lead to fast retransmission.

The normal three-way handshake is SYN, SYN-ACK, and ACK. Sequence numbers identify positions in the TCP byte stream, while acknowledgment numbers indicate the next sequence value the receiver expects. You do not need to calculate every value to diagnose common failures.

A zero-window condition means the receiver temporarily advertises that it cannot accept more data. This can point to an overloaded application, a slow reader, or constrained receive buffers. A complete handshake followed by a long application delay means basic TCP connectivity works; continue with application, TLS, server-load, or dependency investigation.

Diagnosing common packet patterns

Observed patternLikely causesNext checks
DNS query without responseResolver unreachable, firewall, routing failure, or unavailable resolverVerify the configured resolver, route, ACLs, and capture location.
Repeated SYN without SYN-ACKFiltering, incorrect destination, route issue, server failure, or lossCapture nearer the client and server; inspect routes, firewalls, and listener status.
Immediate RSTNo listener, active rejection, or an intermediary resetCheck the service binding, port, firewall behavior, and which device sent the RST.
ARP requests without repliesWrong address, VLAN or switch problem, gateway failure, or layer-2 reachability issueCheck subnet configuration, VLAN membership, gateway status, and neighbor presence.
ICMP unreachable messagesRouting failure, administratively blocked traffic, or unavailable destinationIdentify the sender and code, then inspect routes and filtering.
Capture dropsTraffic rate exceeds capture buffers or processing and storage capacityNarrow the filter, reduce display work, check resources, and repeat from a better capture point.

Capture evidence helps separate problem domains. No SYN leaving the client suggests a local application or client-side issue. SYN packets leaving but no response arriving suggests a path, firewall, server, or capture-location issue. A complete handshake shifts attention above TCP. DNS and ARP observations can identify name-resolution and local-link failures before application testing begins.

Saving and reading pcap files

Use -w to write binary packet records to a pcap file:

sudo tcpdump -i eth0 -nn -w incident.pcap 'host 192.0.2.25 and tcp port 443'

When writing with -w, tcpdump does not print the normal packet summaries to the terminal. The filter still applies during collection. Stop with Ctrl+C, then read the file:

tcpdump -nn -r incident.pcap

You can apply a display-time filter while reading:

tcpdump -nn -r incident.pcap 'tcp port 443'

A pcap is binary capture output, not a text log. It preserves packet bytes and metadata for tools such as Wireshark, which can reconstruct conversations and provide deeper protocol analysis. Text output is convenient for quick review but cannot preserve all information in a reusable packet-analysis format.

Choose unique filenames and check before starting. Do not unintentionally overwrite an existing investigation:

test ! -e incident.pcap && sudo tcpdump -i eth0 -nn -w incident.pcap 'host 192.0.2.25'

Use a controlled directory and restrictive permissions for sensitive captures. A capture intended for Wireshark should normally retain enough of each packet for the protocols and payloads that must be analyzed.

Long-running and high-volume captures

An unrestricted capture can fill a disk quickly. Reduce volume before increasing storage:

  • Filter by the affected host, protocol, port, and time window.
  • Use -c when a fixed sample is sufficient.
  • Use a suitable snapshot length with -s when full payloads are not required.
  • Write to a filesystem with known capacity and monitor free space.
  • Avoid -v, -vv, -A, or -X during very busy captures unless their output is necessary.

Rotate files by size and retain a bounded number:

sudo tcpdump -i eth0 -nn -w capture.pcap -C 100 -W 10 'tcp port 443'

This requests approximately 100 MB files and a set of 10 files. Exact naming and overwrite behavior can vary by tcpdump version, so test the rotation policy before relying on it for evidence. Time-based rotation uses -G with a filename template appropriate to the installed implementation. Combining rotation with a file limit prevents an unattended capture from growing forever.

At the end of a live capture, inspect the statistics. Kernel drops mean packets arrived faster than tcpdump or the capture buffer could process them. Narrow filters, remove terminal decoding, use an appropriate snapshot length, improve storage capacity, or capture closer to the relevant endpoint. A capture with drops may still be useful, but conclusions about missing packets must be qualified.

Payload inspection and output formatting

For authorized, unencrypted test traffic, -A prints payload bytes as ASCII:

sudo tcpdump -i eth0 -nn -A 'tcp port 80'

Use -X for hexadecimal bytes alongside an ASCII representation:

sudo tcpdump -i eth0 -nn -X 'tcp port 80'

ASCII output can help verify a simple unencrypted protocol exchange. Hex output is useful for binary protocols, delimiters, and bytes that do not render as text. Both options produce substantial noise and may expose credentials or other sensitive payloads.

Encrypted traffic such as normal HTTPS generally does not yield meaningful application text from tcpdump alone. The capture still provides valuable metadata and transport evidence, but payload interpretation requires authorized keys, endpoint instrumentation, or application-level logs. Do not attempt to defeat encryption without explicit authorization.

Operational workflow for network diagnosis

  1. Define the symptom: record the affected host, destination, service, port, protocol, source network, and timeframe.
  2. Choose the capture location: identify the interface and whether the client, server, gateway, relay, bridge, container namespace, or another point can see the relevant packets.
  3. Start narrowly: begin with a host, protocol, and port filter rather than capturing everything.
  4. Reproduce once or within a defined window: note the exact time and test action.
  5. Compare expected and observed flow: for TCP, look for SYN, SYN-ACK, ACK, data, and teardown; for DNS, compare queries and responses; for ARP, compare requests and replies.
  6. Save evidence: write a filtered pcap when later review or escalation is needed.
  7. Check capture quality: review packet-drop statistics and confirm that the selected interface and snapshot length were adequate.
  8. Protect the result: restrict access, document handling, and remove the file according to policy after the investigation.

Use the simplest filter that answers the question. For example, a service-reachability test can begin with:

sudo tcpdump -i eth0 -nn -c 50 'host 192.0.2.25 and tcp port 443'

Then save a larger, carefully controlled capture only if the first observation requires more evidence.

Practical capture examples

Identify interfaces

tcpdump -D

Generate a small amount of known traffic, such as a test connection, and observe which interface shows it. Include loopback or a virtual interface when the client and service run on the same host or inside a namespace.

Check whether a service receives connections

sudo tcpdump -i eth0 -nn 'tcp port 8443'

A SYN followed by SYN-ACK and ACK indicates that the TCP path and listener participated in a handshake. Repeated SYN packets without a reply require path, firewall, destination, and capture-point checks. An immediate RST commonly means active rejection or no listener.

Capture one web server conversation

sudo tcpdump -i eth0 -nn -c 50 host 192.0.2.25

Add a protocol or port when unrelated traffic from that host is still too noisy:

sudo tcpdump -i eth0 -nn 'host 192.0.2.25 and tcp port 443'

Collect a pcap for Wireshark

sudo tcpdump -i eth0 -nn -w incident.pcap 'host 192.0.2.25 and tcp port 443'
tcpdump -nn -r incident.pcap

Use the pcap in Wireshark for conversation following, protocol trees, timing graphs, and additional display filters. Keep the original file protected and record the interface, filter, time, and system that produced it.

Common mistakes and troubleshooting

  • No packets appear: verify the interface, privileges, filter syntax, traffic direction, and whether the traffic is actually generated during the capture.
  • Names slow or obscure output: use -nn to disable hostname and service-name resolution.
  • The physical interface shows nothing: traffic may be on loopback, a bridge, tunnel, VPN, container, or namespace interface.
  • Expected payload is missing: check snapshot length, encryption, encapsulation, and whether the relevant bytes were available at the capture point.
  • Too much output: write a pcap, narrow the BPF filter, lower verbosity, or limit packets with -c.
  • Packets seem duplicated: captures on bridges, multiple interfaces, or mirrored links may observe the same traffic more than once.
  • Capture statistics report drops: reduce traffic and display processing, increase capacity where appropriate, and repeat the capture.
  • A port filter misses traffic: confirm whether the protocol uses another port, IPv6, a tunnel, or an encrypted proxy connection.

Exam-relevant notes

  • -D lists interfaces; -i selects one.
  • -n disables hostname lookup, while -nn also prevents service-name lookup for ports.
  • -c limits packets, -s controls snapshot length, and -p disables promiscuous mode.
  • -w writes a binary pcap; -r reads one.
  • -A displays ASCII payload and -X displays hexadecimal plus ASCII.
  • Capture filters use BPF expressions such as host, net, port, src, dst, and, or, and not.
  • A TCP handshake is SYN, SYN-ACK, then ACK.
  • Repeated SYN packets without a response differ from an immediate RST: the former indicates no observed acceptance, while the latter indicates an active reset.
  • A pcap preserves packet data for later analysis; terminal text is only a rendered summary or payload view.
  • Missing packets may reflect actual network loss or capture drops. Always check the end-of-capture statistics.