AlgoMaster Logo

tcpdump for the Command Line

Medium Priority67 min readUpdated August 14, 2026
Listen to this chapter
Unlock Audio

tcpdump captures and inspects packets from a terminal. It is available on servers where a graphical environment is absent, works over SSH, and can write standard capture files for later analysis.

Its compact interface is valuable during incidents:

This command selects an interface, disables name conversion, and captures both directions of one host's HTTPS traffic.

The short command hides several decisions. The chosen interface determines which traffic is visible. The filter determines which packets survive collection. Output options determine whether tcpdump prints a summary, displays payload bytes, or stores the original packet data. A mistake in any of these areas can remove the evidence needed for diagnosis.

This chapter develops a practical command-line workflow for selecting interfaces, writing capture filters, reading packet summaries, saving bounded capture files, and collecting traffic safely from remote systems.

How tcpdump Processes Traffic

tcpdump uses a packet-capture library such as libpcap to receive packet records from an interface. A capture filter is compiled into a packet-matching program and applied as early as the platform allows. Packets that fail the filter are not delivered to tcpdump for normal processing.

There are three different outcomes in this pipeline:

  • Traffic outside the observation point never reaches the capture mechanism.
  • Traffic rejected by the filter is deliberately excluded.
  • Traffic accepted by the filter can still be lost if capture buffers overflow.

The final packet counters help distinguish the last two cases, but no local counter can report packets that never reached the selected interface.

tcpdump uses capture-filter syntax, commonly called pcap or BPF filter syntax. It does not accept Wireshark display expressions such as tcp.port == 443 or http.response.code >= 500.

Command Structure

A tcpdump command has three parts:

  • sudo represents the permission needed for live packet capture on many systems. A configured capture group, capability, or platform service can remove the need for it.
  • Options control the interface, output, packet count, timestamps, snapshot length, and capture files.
  • The expression decides which packets match.

Place options before --. The -- delimiter marks the end of command options. Quote the complete filter expression so the shell does not interpret parentheses, &, |, <, or > before tcpdump receives them.

For Unix-like shells, single quotes are the usual choice:

Windows cmd.exe requires double quotes instead of single quotes.

If no filter expression is supplied, tcpdump captures every packet visible on the interface. On an active server, that can produce more output, CPU work, and disk usage than intended.

Selecting an Interface

List capture interfaces with:

The output contains interface numbers, names, and sometimes descriptions. Select one explicitly:

Common interface names include:

  • eth0, ens5, or enp0s3 for Ethernet on Linux
  • wlan0 for Wi-Fi on Linux
  • en0 for Ethernet or Wi-Fi on macOS
  • lo on Linux and lo0 on macOS for loopback
  • tun0, utun3, or similar names for VPN tunnels
  • bridge and virtual Ethernet names created by containers or hypervisors

The default interface chosen by tcpdump may not carry the traffic under investigation. Always pass -i during a diagnosis.

The any Pseudo-Interface

On supported platforms, -i any captures from regular operating-system interfaces:

This is useful for discovering whether traffic uses a physical interface, loopback, a VPN, or a virtual interface. It has tradeoffs:

  • Captures on any are not performed in promiscuous mode.
  • Link-layer output can use a cooked capture format instead of native Ethernet.
  • A packet crossing multiple host interfaces, such as a container veth and bridge, can appear at more than one observation point.
  • Interface support and output details vary by platform.

Use any to locate the path, then capture on a specific interface when exact link-layer fields and packet counts matter.

Loopback Traffic

A request to 127.0.0.1 or ::1 uses loopback. Capture it with:

Use lo0 instead of lo on macOS.

The loopback link-layer header is platform-specific. It will not contain the Ethernet addresses expected from a physical LAN capture.

Capture Direction

Some platforms support -Q to restrict capture direction:

The accepted values are commonly in, out, and inout. Direction capture is not available on every platform or interface.

Both directions are normally needed to relate requests to replies, TCP data to acknowledgments, and DNS queries to responses. Use -Q only when a one-direction capture answers the question.

Options Used in Daily Analysis

The following options cover the main capture and inspection workflows:

OptionPurpose
-i interfaceSelect the capture interface
-nKeep addresses and ports numeric instead of resolving names
-c countStop after the given number of matching packets
-s snaplenStore at most this many bytes from each packet
-w fileWrite raw packet records to a capture file
-r fileRead packets from a saved capture file
-v, -vv, -vvvPrint progressively more decoded detail
-ePrint the link-layer header
-APrint packet bytes after the link header as ASCII
-XPrint packet bytes after the link header in hexadecimal and ASCII
-XXInclude the link-layer header in hexadecimal and ASCII output
-SPrint absolute TCP sequence numbers
-tttPrint time since the previous output line
-ttttPrint calendar date and time
-tttttPrint time since the first output line
-B sizeSet the capture buffer size in KiB
-C sizeRotate files after a size threshold
-W countLimit rotated files or file count
-G secondsRotate files at a time interval

-n avoids host and service-name conversion. Many tcpdump commands write it as -nn; current builds commonly accept the repeated form. Numeric output prevents local name resolution from obscuring the exact address and port in the packet.

Options can be grouped:

The expanded form is easier to review in operational runbooks:

Reading a TCP Output Line

Consider output captured with numeric addresses, calendar timestamps, verbose decoding, and absolute TCP sequence numbers:

Read it from left to right.

Timestamp

The capture system assigned this timestamp to the packet. It is not a timestamp transmitted in the TCP header.

Network Protocol

This record contains IPv4. IPv6 output begins with IP6.

Source and Destination

The source is 10.0.0.8:51542, and the destination is 203.0.113.20:443. tcpdump separates an IP address from its transport port with a dot, so 51542 and 443 are not additional IP octets.

The > arrow shows packet direction for this line. The response reverses the endpoints:

TCP Flags

The main flag symbols are:

  • S for SYN
  • . for ACK
  • F for FIN
  • R for RST
  • P for PSH
  • U for URG
  • W for CWR
  • E for ECE
  • e for AE

Flags can be combined:

The dot inside a flag set means ACK. It is different from punctuation outside the brackets.

Sequence and Acknowledgment Numbers

The SYN carries the sender's initial sequence number. -S requested absolute sequence values.

Without -S, tcpdump normally displays relative sequence values after it has enough connection context. A data range such as:

means the segment carries 500 bytes at stream positions 1 through 500, and the peer's next expected byte is 1 in the opposite direction.

Window

This is the Window field advertised by the packet sender. A negotiated TCP window-scale factor can make the effective receive window larger. The scale factor comes from that sender's SYN and should not be applied to the window field inside SYN packets.

TCP Options

This SYN advertises a maximum segment size, SACK support, timestamps, padding, and a window-scale value. Later packets usually contain a smaller set of options.

Payload Length

For TCP output, length is the TCP payload length. It does not include the Ethernet, IP, or TCP headers. SYN and ACK-only packets commonly show zero even though bytes were transmitted on the network.

Loading simulation...

Timestamp Modes

The default timestamp shows time since local midnight. Different modes support different analysis tasks.

Use calendar timestamps to correlate with logs:

Use a delta from the previous printed packet:

Use a delta from the first printed packet:

-ttt measures the gap between consecutive output lines. If the filter contains several connections, the two lines can belong to different TCP streams. Narrow the filter to one endpoint pair and port pair before treating the delta as connection timing.

Timestamps reflect the capture clock and the point where the operating system timestamps packets. Separate hosts can have clock offsets. Compare absolute times across captures only after checking clock synchronization and offset.

Reading Other Protocols

tcpdump formats output according to the decoded protocol.

A UDP packet has no TCP flags, sequence number, acknowledgment, or window:

A DNS query can receive a higher-level summary:

The transaction ID is 1250, the + indicates recursion desired in common output, and the question asks for an A record.

An ARP request reads more like a sentence:

An ICMP error can include information from the packet that triggered it. Capture enough bytes to preserve the embedded header when diagnosing unreachable ports or MTU problems.

Protocol output varies by tcpdump version and verbosity level. Treat the decoded line as a view of the captured bytes rather than a stable machine-readable format.

Capture Filter Language

A basic filter primitive can have three qualifiers:

For example:

  • tcp is the protocol qualifier.
  • dst is the direction qualifier.
  • port is the type qualifier.
  • 443 is the value.

Omitted qualifiers use broader defaults. host 10.0.0.8 checks either source or destination. port 53 checks supported transport protocols and both directions.

Filtering by Protocol

Capture one protocol:

Restrict IP version explicitly:

Filtering by Host

Traffic to or from one address:

Only packets sourced by that address:

Only packets sent to that address:

Traffic between two specific hosts:

A hostname can be used, but it is resolved when the filter is prepared. Numeric addresses make the selected endpoints explicit and avoid changes caused by DNS answers.

Filtering by Network

IPv4 subnet:

IPv6 prefix:

Source subnet only:

Filtering by Port

Both directions of TCP port 443:

Requests sent to a service port:

Replies sent from that service port:

A port range:

dst port 443 excludes server replies because those packets have source port 443. Capture port 443 when the complete exchange is needed.

DNS can use UDP or TCP:

Filtering by MAC Address and VLAN

One Ethernet address in either direction:

Ethernet broadcasts:

Traffic tagged with VLAN 100:

IPv4 traffic inside VLAN 100:

The vlan keyword changes the header offsets used for the rest of that filter path. Nested VLANs require an additional vlan qualifier for each tag. Host offloads and switch configuration can also remove a VLAN tag before the selected capture point.

Combining Filter Conditions

Use and, or, and not to build larger expressions:

Negation binds tightly. The precedence of and and or in pcap filter syntax should not be inferred from a programming language. Parentheses make the intended grouping explicit.

Compare these expressions:

The second form clearly requires the host condition for both ports.

Quoting is part of command correctness:

Without quotes, the shell can treat parentheses and logical symbols as command syntax.

Filtering TCP Flags

The pcap filter language can inspect bytes at fixed protocol offsets. TCP control bits are available through named values.

All TCP packets with SYN set:

Initial SYN packets with SYN set and ACK clear:

Packets with RST set:

Connection setup, close, or reset signals:

Use the expression in a command:

The bitwise expression tests whether the selected bit remains nonzero after applying a mask. It does not require the flag to be the only bit set.

Limits of Byte-Offset Filters

The general accessor syntax is:

For example, tcp[13] reads the byte containing the eight classic TCP flags. Named accessors such as tcp[tcpflags] make the intent clearer.

Fixed-offset expressions are sensitive to encapsulation and protocol structure:

  • Transport-layer byte accessors do not reliably handle IPv6 extension-header chains.
  • Noninitial IP fragments do not contain a TCP header.
  • VLAN and tunnel headers can change offsets at the link or network layer.
  • A truncated capture can omit the requested bytes.

The current pcap filter implementation does not apply TCP byte accessors to IPv6 packets. Capture the relevant IPv6 TCP traffic with ip6 and tcp, then inspect the printed flags or analyze the saved file.

Use ordinary host, network, port, and protocol primitives when they can express the requirement. They are easier to review and less dependent on packet layout.

Printing Packet Detail

The default one-line summary is suitable for a fast check. Additional output options expose more information.

Verbosity

Add -v for fields such as IP TTL, ID, total length, and fragmentation details:

-vv and -vvv request progressively more protocol-specific detail. More decoding consumes CPU and creates more terminal output. Save raw packets when later analysis may require details that are not part of the current text format.

Add -e to print link-layer information:

On Ethernet, this includes source and destination MAC addresses, the EtherType, and frame length. The fields differ on loopback, cooked, Wi-Fi, and tunnel captures.

ASCII Payload

Add -A to print packet bytes after the link-layer header as ASCII:

Plaintext HTTP lines can become readable, mixed with dots for nonprintable header bytes. TCP segmentation still applies, so one application message can be split across several packet outputs.

Hexadecimal and ASCII

Add -X for hexadecimal and ASCII:

Use -XX when the link-layer header bytes are also needed.

Payload printing can expose cookies, credentials, API keys, request bodies, and personal data. TLS payload appears as encrypted binary data unless capture-time decryption is performed elsewhere.

Writing Packets to a File

Terminal output is convenient for a narrow question. A raw capture file preserves packet bytes for repeatable analysis.

-w api.pcap writes packet records instead of printing the normal decoded lines. tcpdump does not choose a file format from the extension alone; .pcap is a useful convention for tools and users.

-s 0 is widely used to request the implementation's default maximum snapshot length. Current tcpdump already uses a large default, so omitting -s is often equivalent. Avoid a small snapshot unless the required headers and payload boundaries are known.

Stop the capture with Ctrl+C. tcpdump prints capture counters after it exits.

Limit by Packet Count

Capture the first 2,000 matching packets:

The count applies after the capture filter. Traffic rejected by the filter does not advance it.

Rotate by File Size

Create a bounded ring of ten files, rotating at approximately 100 million bytes:

With -C, a plain numeric size uses millions of bytes. tcpdump adds numeric suffixes to rotated files. When the file-count limit is reached, size-based rotation begins overwriting earlier files.

This design keeps the newest bounded window of traffic. Overwritten files cannot be recovered from the ring.

Rotate by Time

Create a new file every five minutes and stop after twelve files:

The filename contains time-format placeholders so each rotation produces a distinct path. If the generated filename repeats, tcpdump can overwrite an earlier file.

The interaction between -C, -G, and -W varies by combination. Choose either a clear size-based ring or a clear time-based series instead of combining both rotation models without testing the exact tcpdump build.

Flush Packets for a Live Consumer

-U asks tcpdump to flush each packet record promptly:

This is useful when another process reads the file or standard output during capture. More frequent writes can increase overhead.

Reading a Saved Capture

Read a capture file with:

Reading a file does not require packet-capture privilege, although file permissions still apply.

Apply the same pcap filter language while reading:

The filter changes which records tcpdump prints. It does not remove packets from api.pcap.

Inspect the first 20 matching packets with detailed TCP output:

Print matching packet bytes:

The -w and -r workflow separates evidence collection from interpretation:

The same capture can be read several times with different filters, timestamp modes, verbosity levels, and payload views. Graphical analyzers can also open the file when stream reconstruction or field-level display filters are needed.

Capture Counters and Packet Drops

After a live capture stops, tcpdump reports counters similar to:

The exact meaning of received by filter varies by operating system. It can count packets that matched the filter, packets offered to the capture mechanism, or another platform-specific stage.

Packets dropped by kernel is the main warning that the local capture path ran out of buffer space before tcpdump processed all available packet records. These are capture drops, not proof that the network dropped the same packets.

Capture drops can increase when:

  • The packet rate is high.
  • The filter is too broad.
  • Verbose text or payload output consumes CPU.
  • The process is not scheduled promptly.
  • Storage cannot keep up.
  • The capture buffer is too small.

Increase the buffer on supported systems with -B, whose value is in KiB:

A larger buffer absorbs short bursts but does not fix sustained processing or storage limits. Narrow the filter, write raw packets instead of decoding live, reduce capture scope, or move the observation point when drops continue.

Remote Capture over SSH

tcpdump is commonly run on a remote server through SSH. The management connection becomes part of the server's traffic, so a broad capture can include the SSH session used to operate tcpdump.

Exclude the management port when it is unrelated:

Adjust port 22 if SSH uses a different port. Do not exclude it when SSH itself is the failing service.

A capture can also stream raw pcap bytes over SSH:

This form assumes noninteractive capture permission on the remote host:

  • -w - writes binary pcap data to standard output.
  • -U flushes each packet promptly.
  • The local redirection writes the SSH payload to server.pcap.
  • Excluding the SSH connection prevents captured pcap bytes from generating additional captured SSH packets in a feedback loop.

Do not send -w - directly to a terminal. Binary pcap output is not text and can corrupt the display. Remote warnings and permission prompts must also remain on standard error rather than being mixed into the pcap stream.

Saving a bounded file remotely and transferring it after the reproduction is easier to audit when live streaming is unnecessary.

Capturing Container and Virtual-Machine Traffic

Container traffic can cross several host networking layers:

A capture inside the container's network namespace can show its own addresses before host NAT. A capture on the host bridge can show container addresses and peer traffic. A physical-interface capture can show translated host addresses or tunnel packets.

Use -i any to discover candidate interfaces, then select the interface that represents the side of NAT, proxying, or tunneling relevant to the question. Seeing similar packets on multiple virtual interfaces does not mean the network duplicated them.

The same reasoning applies to virtual machines, service meshes, VPNs, and host-level proxies. Record the namespace and interface with the capture.

Loading simulation...

Practical Diagnostic Filters

A Client Cannot Connect

Capture the service traffic and network-layer error messages:

For an IPv6 endpoint, use its IPv6 address and capture ICMPv6:

Possible patterns include:

  • Repeated SYN packets with no reply
  • A SYN followed by a RST
  • A complete handshake followed by an application delay
  • An ICMP unreachable or packet-too-big message

A filter containing only tcp port 443 can miss ICMP errors that explain why the connection failed.

DNS Appears Slow

Capture both UDP and TCP DNS:

Match transaction IDs, addresses, ports, and question names. A repeated UDP query can indicate that no usable response arrived at the capture point. A later TCP exchange can follow truncation or another fallback condition.

Connections Reset

For IPv4 traffic, isolate RST packets:

The source address and port identify which observed endpoint sent the reset. A capture on only one side cannot prove whether an intermediary generated or rewrote it elsewhere in the path.

One TCP Connection Is Slow

If both endpoint addresses and both ports are known:

This narrows -ttt deltas to one four-tuple. Inspect the handshake, payload sequence ranges, acknowledgments, receive window, and repeated sequence ranges.

tcpdump does not maintain Wireshark-style generated fields such as tcp.analysis.retransmission. A repeated sequence range can indicate retransmission, but confirming it requires both directions and enough earlier packets to establish stream state.

Local Address Resolution Fails

Capture ARP for an IPv4 neighbor:

Repeated requests without a reply show that the capture point observed the sender asking but did not observe a matching ARP response. Interface selection, VLAN placement, and capture loss still need to be checked.

Guided Capture: One Local HTTP Request

This walkthrough creates a small plaintext exchange on loopback.

1. Start the Server

Run:

2. Start tcpdump

On macOS:

On Linux, replace lo0 with lo.

This command:

  • Captures loopback TCP port 8000 in both directions
  • Keeps addresses and ports numeric
  • Shows time relative to the first printed packet
  • Uses absolute sequence numbers
  • Adds verbose header detail
  • Prints ASCII packet bytes

3. Send a Request

In another terminal:

The missing path normally produces an HTTP error response.

4. Stop and Read the Output

Press Ctrl+C in the tcpdump terminal. Identify:

  1. The SYN, SYN-ACK, and ACK
  2. The client ephemeral port and server port 8000
  3. The packet containing the HTTP request line
  4. The first response packet
  5. The close sequence
  6. The final capture counters

The packet count and segmentation can vary by operating system and offload behavior. Follow sequence ranges and flags rather than expecting one fixed number of lines.

5. Repeat into a Capture File

Start a file capture:

Use lo on Linux. Send the request again, then stop tcpdump with Ctrl+C.

Read the file:

The sudo on the read command is needed only if the saved file is not readable by the current user. Reading packet data itself requires no capture privilege.

Stop the Python server with Ctrl+C after the walkthrough.

Capture Artifacts and Operational Risks

Checksum Offload

An outbound host capture can occur before the network interface writes final TCP or UDP checksums. tcpdump may report a bad checksum even though the transmitted packet was valid.

Capture from another host or a network tap when on-wire checksum validation matters. Some builds provide an option to disable checksum verification, but hiding the warning does not determine whether offload caused it.

Segmentation and Receive Offload

Host captures can show large TCP payloads before transmit segmentation or after receive aggregation. Packet size and count may therefore differ from an external wire capture.

Sequence numbers still describe the TCP byte stream. Use a consistent observation point when comparing byte ranges and timing.

Snapshot Truncation

A small -s value stores only the beginning of each packet. tcpdump marks truncation with output such as:

or another protocol name. Missing payload and incomplete headers can prevent later decoding. A narrow snapshot cannot be repaired after capture.

Capture Buffer Drops

Kernel drops create holes in the capture file that can resemble network loss. Check the final counters before interpreting missing sequence ranges or responses.

Broad Filters

An unrestricted capture can consume CPU, memory bandwidth, and disk space. It can also collect unrelated secrets and personal data. Bound the interface, time, file size, and traffic scope.

Filters That Are Too Narrow

A filter can remove causal traffic:

  • tcp port 443 excludes the preceding DNS exchange.
  • dst port 443 excludes server replies.
  • A service-only filter excludes ICMP errors.
  • An IP-only filter excludes ARP.
  • A client-address filter can miss traffic after NAT or proxy termination.

Start from the observable question and include the protocols needed to explain both success and failure.

Sensitive Packet Data

Capture files and -A or -X output can expose credentials, cookies, tokens, database queries, internal hostnames, and request bodies. Restrict access, use bounded retention, and inspect data before sharing it.

Encryption protects application content but still leaves endpoint, timing, size, and transport metadata visible.

Common Misunderstandings

tcpdump filters are capture filters. Wireshark display fields such as tcp.stream and http.response.code are not valid pcap filter expressions.

The default interface is not necessarily the relevant interface. Specify -i and account for loopback, VPN, bridge, and virtual interfaces.

dst port 443 does not capture a complete HTTPS connection. Replies normally use source port 443.

length in a TCP summary is payload length. It is not the complete frame or IP packet size.

The dot in Flags [.] means ACK. It is part of the flag notation.

Relative sequence numbers differ from transmitted values. Use -S when absolute sequence values are required.

-ttt is the delta from the previous printed packet. A broad filter can place unrelated conversations on adjacent lines.

-w writes raw packet records instead of the normal decoded text. Read the file later with -r.

A read-time filter does not modify the capture file. It controls only which records tcpdump processes and prints.

A missing packet in tcpdump output does not prove network loss. The packet may be outside the capture point, rejected by the filter, dropped by the capture mechanism, or truncated before useful fields.

Kernel capture drops are not network packet drops. They report loss in the local observation pipeline.

A bad outbound checksum can be an offload artifact. The host can capture a packet before hardware completes the checksum.

-A cannot turn encrypted TLS payload into HTTP text. It prints the encrypted bytes as character output.

The any interface is useful for discovery but changes capture semantics. It can use cooked link-layer headers and observe traffic at several host interfaces.

Byte-offset filters are layout-dependent. IPv6 extension headers, fragmentation, VLANs, and tunnels can invalidate assumptions made for a basic IPv4 TCP packet.

Summary

tcpdump captures and inspects packets from a terminal. Use -D to list devices, -i to select the observation point, and -n to avoid name conversion. Quoted pcap expressions filter by protocol, host, network, port, direction, flags, or link properties; they are not Wireshark display filters. Parentheses clarify mixed and, or, and not logic.

TCP output shows endpoints, flags, sequence ranges, acknowledgments, windows, options, and payload length. Time flags provide delta, calendar, or capture-relative views, while verbosity, link-header, ASCII, hex, and absolute-sequence options expose more detail.

Use -w to preserve raw packets and -r for repeatable offline analysis. Bound captures by packet count, file size, rotation count, or duration, then check drop counters because local loss can resemble network loss.

Interface selection, management traffic, snapshot truncation, offloads, and multi-interface visibility can alter the trace. Captures may contain sensitive data and require restricted collection, storage, and sharing.

Choose the observation point and reviewed filter explicitly, capture enough context in both directions, preserve bounded raw evidence, and verify drop counters.

Quiz

tcpdump for the Command Line Quiz

5 quizzes