Linux online course

tcpdump Command in Linux: Capture and Analyze Network Packets

Learn how to use tcpdump on Linux to capture live traffic, write and read pcap files, build BPF filters, interpret TCP packets, and troubleshoot network problems.

tcpdump is a Linux command-line utility for capturing and inspecting network packets. It can display traffic live as packets arrive or save packets to a pcap file for later analysis with tcpdump or Wireshark.

This guide covers interface selection, permissions, output formats, Berkeley Packet Filter expressions, capture-file rotation, and a practical troubleshooting workflow.

What tcpdump is used for

A packet capture is a collection of network packets observed on an interface. A network interface can be physical, virtual, loopback, wireless, or an aggregate capture interface such as any. tcpdump sees traffic that is visible to the selected interface; it does not automatically see every packet on the network.

Common diagnostic uses include:

  • Confirming that packets reach a host and that replies leave it.
  • Checking whether an application uses the expected protocol and port.
  • Investigating failed TCP connections, DNS lookups, HTTP requests, and API calls.
  • Distinguishing packet loss, resets, unreachable messages, and application-level failures.
  • Preserving traffic for deeper analysis in a graphical protocol analyzer.

Because tcpdump exposes low-level network information, use a narrow filter whenever possible. Narrow filters reduce terminal output, CPU work, file size, and accidental collection of unrelated traffic.

Permissions, installation, and safe operation

Capturing packets typically requires root privileges or suitable Linux capabilities. The simplest approach is to run tcpdump with sudo:

sudo apt install tcpdump
sudo dnf install tcpdump

The first command is suitable for Debian and Ubuntu systems. The second is commonly used on Fedora, RHEL-derived, and similar systems. Follow your distribution's package-management policy.

Before capturing, confirm that you have organizational authorization, understand the privacy requirements, and know where the resulting files will be stored. A pcap file is not harmless diagnostic text: it may contain complete application data. Restrict file permissions, avoid world-writable directories, monitor disk usage, and securely delete captures when retention is no longer required.

Basic live capture

Start and stop a capture

With no filter, tcpdump captures a large amount of traffic on its default interface and prints a line for each matching packet:

sudo tcpdump

On a busy system, the output can scroll rapidly. Press Ctrl+C to stop. tcpdump then prints capture statistics, including packets received by the filter and packets dropped by the capture mechanism when applicable.

Find and select an interface

List interfaces that tcpdump can use:

sudo tcpdump -D
ip link show

Interface names often include eth0, ens33, wlan0, or lo. Capture on a selected interface with -i:

sudo tcpdump -i eth0

Replace eth0 with the actual interface name. Selecting the correct interface is important: traffic on a wireless, Ethernet, VPN, container, or loopback interface may not appear on another interface.

The any pseudo-interface

sudo tcpdump -i any

any is a Linux pseudo-interface that can collect traffic from multiple interfaces. It is useful when you do not yet know which interface carries the traffic. However, it is not identical to capturing on one physical interface. Link-layer headers and packet direction can differ, and some interface-specific capture features may not behave the same way. Use a specific interface when you need precise link-layer or direction information.

Understanding tcpdump output

A representative TCP line might look similar to this:

14:22:31.481920 IP 192.0.2.10.51544 > 198.51.100.20.443: Flags [S], seq 123456789, win 64240, options [...], length 0
FieldMeaningTroubleshooting value
timestampTime at which tcpdump observed the packetCompare request, response, timeout, and retransmission timing
protocolIP, IP6, ARP, and other protocol labelsShows which network protocol is involved
source host/IP and portThe endpoint sending the packet and its transport portIdentifies the client or server side of a conversation
destination host/IP and portThe endpoint receiving the packet and its transport portConfirms the intended service and direction
TCP flagsControl indicators such as SYN, ACK, FIN, and RSTReveals connection establishment, closure, acknowledgement, or rejection
sequence and acknowledgement numbersTCP byte-position and acknowledgement informationHelps identify retransmission, ordering, and missing responses
window sizeThe advertised amount of data the receiver can acceptCan indicate flow-control conditions

The source is the endpoint sending a packet; the destination is the endpoint receiving it. A port is a transport-layer number identifying an application service or connection endpoint.

tcpdump may resolve addresses to hostnames and ports to service names. Use -n to suppress hostname lookup and -nn to keep both addresses and ports numeric:

sudo tcpdump -n
sudo tcpdump -nn

Numeric output is usually clearer for troubleshooting and avoids delays or confusing names from reverse DNS and service databases.

Display formats and verbosity

OptionPurposeExample useNotes
-iSelect an interface-i eth0Use the name reported by -D or ip link
-DList capture-capable interfacestcpdump -DUseful before choosing -i
-nDisable hostname resolution-nAddresses remain numeric
-nnDisable hostname and service-name resolution-nnAddresses and ports remain numeric
-APrint payload as ASCII-A -s 0Useful for permitted, unencrypted text protocols
-XPrint hexadecimal and ASCII data-XUseful for inspecting printable and binary content together
-xxShow packet-level hexadecimal data, including link-layer information where supported-xxOutput depends on link-layer type
-v/-vv/-vvvIncrease protocol detail-vvMore verbosity produces more output
-ttttPrint full date and time-ttttHelpful when correlating events with logs
-cStop after a packet count-c 100Useful for short, bounded samples
-wWrite packets to a binary capture file-w capture.pcapTerminal output is not the normal live summary
-rRead a saved capture-r capture.pcapCan be combined with display filters
-CRotate files by approximate size in megabytes-C 50Useful on busy interfaces
-GRotate files by time interval in seconds-G 300Often paired with a timestamped filename
-WLimit the number of rotated files-W 5Check platform-specific rotation behavior

For permitted unencrypted HTTP-style traffic, ASCII output can reveal request lines and headers:

sudo tcpdump -A -s 0 'tcp port 80'

Use hexadecimal plus ASCII output when you need both byte values and readable characters:

sudo tcpdump -X -nn 'host 192.168.198.2'

-s 0 requests a full snapshot length, so payloads are not truncated by a small capture limit. Use it only when complete packets are necessary and permitted. Ordinary tcpdump display cannot turn TLS or HTTPS ciphertext into readable application text.

Capture filters and BPF expressions

A BPF filter is a Berkeley Packet Filter expression that selects packets. A filter used during live capture is applied before packets are displayed or written, reducing work and collection. When reading a file with -r, the expression filters packets already collected; it cannot recover packets that were excluded or truncated during capture.

Quote expressions containing parentheses or operators so the shell passes the complete expression to tcpdump. Single quotes are usually the safest choice.

ExpressionMatchesExample
host ADDRESSTraffic to or from an address'host 192.0.2.10'
src host ADDRESSPackets whose source is the address'src host 192.0.2.10'
dst host ADDRESSPackets whose destination is the address'dst host 198.51.100.20'
net NETWORKTraffic involving a network'net 192.0.2.0/24'
tcpTCP packetstcp
udpUDP packetsudp
icmpIPv4 ICMP packetsicmp
arpARP packetsarp
ipIPv4 packetsip
ip6IPv6 packetsip6
port NUMBERTraffic to or from a port'port 443'
src port NUMBERPackets with the specified source port'src port 53'
dst port NUMBERPackets with the specified destination port'dst port 443'
portrange A-BTraffic involving a port range'portrange 8000-8080'
andRequires both conditions'tcp and port 443'
orRequires either condition'icmp or arp'
notExcludes a condition'not port 22'
Parenthesized expressionsGroups conditions and controls logic'tcp and (port 80 or port 443)'

Direction words such as src and dst describe packet endpoints, not necessarily physical inbound or outbound direction. For example, dst port 443 matches packets addressed to port 443, while replies usually have source port 443.

Useful host, protocol, port, and service filters

Focus on one host or protocol

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

The first command captures traffic to or from the selected IPv4 address. The second selects TCP only. The third selects traffic involving port 443, regardless of whether that port is the source or destination.

Combine conditions

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

This narrow filter is useful when diagnosing one HTTPS connection to a particular server. It shows connection metadata and encrypted payload packets, but not readable HTTPS content.

Inspect DNS traffic

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

DNS commonly uses UDP port 53, but TCP port 53 is also used in cases such as larger responses, truncated responses, and zone transfers. Comparing queries with replies can reveal missing responses or DNS errors.

Writing captures to files

Use -w to save packets in a binary pcap-compatible format. A filename ending in .pcap is conventional:

sudo tcpdump -i eth0 -nn -c 100 -w capture.pcap 'host 192.168.198.2'

This writes 100 matching packets and then exits. Unlike normal live display, -w writes packet records rather than presenting the usual human-readable summary in the terminal.

Use a protected directory, check available disk space, and apply a filter before starting a capture on a busy host. The pcap format is widely supported; some tools also use pcapng, but the output produced by tcpdump is commonly pcap.

Limit size and duration

Rotation prevents an ongoing capture from filling a disk. Rotate approximately every 50 MB and retain five files:

sudo tcpdump -i eth0 -nn -C 50 -W 5 -w capture.pcap

Rotate every 300 seconds and use timestamps in filenames:

sudo tcpdump -i eth0 -nn -G 300 -W 12 -w 'capture-%Y%m%d-%H%M%S.pcap'

-C rotates by approximate file size, while -G rotates by time. -W limits the number of rotated files in supported usage. Confirm the resulting filenames and retention behavior on your tcpdump version before relying on them for long-running collection.

Reading saved capture files

Use -r to inspect a saved capture without collecting new traffic:

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

The second command applies a filter while reviewing the file. You can also add display options such as -A, -X, -v, or -tttt when appropriate.

For deeper protocol dissection, open the pcap in Wireshark or use another authorized packet-analysis tool. Collecting a capture and analyzing it later are separate activities: capture settings determine what evidence exists, while analysis settings determine how that evidence is displayed.

TCP connection troubleshooting

TCP is a connection-oriented transport protocol that uses sequencing, acknowledgements, retransmission, and control flags. A normal connection establishment commonly appears as:

  1. The client sends a packet with SYN.
  2. The server replies with SYN, ACK.
  3. The client sends ACK.

FIN is commonly used for orderly connection termination. RST resets a connection and often indicates active rejection by a host or intermediary, although the precise cause requires context. Sequence numbers identify byte positions, acknowledgement numbers confirm received data, and the window size communicates receive capacity.

Observed packet patternLikely meaningNext check
Repeated TCP SYN packetsNo SYN-ACK or other response is arriving; filtering, routing, loss, or an unavailable service may be involvedCheck routes, firewalls, the destination service, and whether the reply reaches the host
TCP RSTA host or intermediary actively reset the connectionCheck service state, firewall policy, and which endpoint sent the RST
ICMP unreachableA network or host reports that delivery or the service is unavailableInspect the ICMP code, routing, and firewall configuration
DNS query without responseThe resolver request may be blocked, lost, misdirected, or unansweredVerify the DNS server address and capture both UDP and TCP port 53
ARP requests without repliesAn IPv4 neighbor is not resolving at the local link layerCheck VLAN, link state, address configuration, and the target host
Normal TCP handshake followed by application failureNetwork connectivity works, but the application, protocol, TLS, authorization, or payload may failInspect subsequent packets and application logs; use a detailed analyzer if needed

A practical troubleshooting workflow

  1. Identify the correct interface with sudo tcpdump -D and ip link show. Confirm the client, server, and resolver addresses.
  2. Start with a restrictive filter for the affected host, protocol, and port.
  3. Begin the capture, then reproduce the failing request while it is running.
  4. Look for the expected request and response. For TCP, check the SYN, SYN-ACK, and ACK sequence; also look for retransmissions and resets.
  5. For DNS, compare each query with its response. For local IPv4 delivery, check ARP requests and replies. For routing or delivery failures, inspect ICMP messages.
  6. Save the capture when deeper inspection or authorized sharing is required.
  7. Stop with Ctrl+C and review tcpdump's packet counters and any dropped-packet report.

A broad diagnostic fallback is useful when the interface is uncertain:

sudo tcpdump -i any -nn

Once traffic is confirmed, switch to a specific interface and narrower expression to reduce noise and collection.

Common problems and fixes

No packets appear

  • The selected interface may be wrong. Recheck tcpdump -D and ip link show.
  • The filter may be too restrictive or incorrectly quoted. Test with sudo tcpdump -i any -nn, then narrow it.
  • The traffic may not traverse this host or interface. Check routing and the application endpoint.
  • Insufficient privileges may prevent capture. Use sudo where authorized and required.
  • Confirm that the application is actually generating traffic.

Names make output confusing

Use -n for numeric host addresses and -nn for numeric addresses and ports. This also avoids lookup delays.

The capture file grows too quickly

Use host, protocol, and port filters. Bound a sample with -c, or rotate by size and time with -C, -G, and -W. Monitor free space and protect the capture directory.

HTTP content is not visible with -A

The session may be HTTPS or another encrypted protocol. Verify the actual service port and protocol, and use -s 0 when complete packets are necessary and authorized. Encryption prevents ordinary packet display from showing application text.

Exam-relevant notes

  • -i selects an interface; -D lists interfaces; -w writes a capture; -r reads one.
  • -n disables hostname resolution. -nn also disables service-name resolution.
  • BPF expressions such as host, net, tcp, port, and, or, and not restrict selected packets.
  • -A displays ASCII payload data, while -X displays hexadecimal and ASCII. Neither decrypts TLS.
  • Repeated SYN packets usually mean expected replies are missing; an RST indicates an active reset, but both require context.
  • A packet capture can contain sensitive application data, so authorization and secure handling are part of correct tcpdump usage.

Related Linux skills

For surrounding administration skills, see Linux command-line topics, Bash shell fundamentals, and managing file ownership for protecting capture files.