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.
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:
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.
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.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.
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 Linuxwlan0 for Wi-Fi on Linuxen0 for Ethernet or Wi-Fi on macOSlo on Linux and lo0 on macOS for loopbacktun0, utun3, or similar names for VPN tunnelsThe default interface chosen by tcpdump may not carry the traffic under investigation. Always pass -i during a diagnosis.
any Pseudo-InterfaceOn 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:
any are not performed in promiscuous mode.Use any to locate the path, then capture on a specific interface when exact link-layer fields and packet counts matter.
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.
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.
The following options cover the main capture and inspection workflows:
| Option | Purpose |
|---|---|
-i interface | Select the capture interface |
-n | Keep addresses and ports numeric instead of resolving names |
-c count | Stop after the given number of matching packets |
-s snaplen | Store at most this many bytes from each packet |
-w file | Write raw packet records to a capture file |
-r file | Read packets from a saved capture file |
-v, -vv, -vvv | Print progressively more decoded detail |
-e | Print the link-layer header |
-A | Print packet bytes after the link header as ASCII |
-X | Print packet bytes after the link header in hexadecimal and ASCII |
-XX | Include the link-layer header in hexadecimal and ASCII output |
-S | Print absolute TCP sequence numbers |
-ttt | Print time since the previous output line |
-tttt | Print calendar date and time |
-ttttt | Print time since the first output line |
-B size | Set the capture buffer size in KiB |
-C size | Rotate files after a size threshold |
-W count | Limit rotated files or file count |
-G seconds | Rotate 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:
Consider output captured with numeric addresses, calendar timestamps, verbose decoding, and absolute TCP sequence numbers:
Read it from left to right.
The capture system assigned this timestamp to the packet. It is not a timestamp transmitted in the TCP header.
This record contains IPv4. IPv6 output begins with IP6.
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:
The main flag symbols are:
S for SYN. for ACKF for FINR for RSTP for PSHU for URGW for CWRE for ECEe for AEFlags can be combined:
The dot inside a flag set means ACK. It is different from punctuation outside the brackets.
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.
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.
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.
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...
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.
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.
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.
Capture one protocol:
Restrict IP version explicitly:
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.
IPv4 subnet:
IPv6 prefix:
Source subnet only:
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:
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.
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.
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.
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:
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.
The default one-line summary is suitable for a fast check. Additional output options expose more information.
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.
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.
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.
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.
Capture the first 2,000 matching packets:
The count applies after the capture filter. Traffic rejected by the filter does not advance it.
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.
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.
-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.
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.
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:
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.
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.server.pcap.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.
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...
Capture the service traffic and network-layer error messages:
For an IPv6 endpoint, use its IPv6 address and capture ICMPv6:
Possible patterns include:
A filter containing only tcp port 443 can miss ICMP errors that explain why the connection failed.
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.
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.
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.
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.
This walkthrough creates a small plaintext exchange on loopback.
Run:
On macOS:
On Linux, replace lo0 with lo.
This command:
In another terminal:
The missing path normally produces an HTTP error response.
Press Ctrl+C in the tcpdump terminal. Identify:
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.
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.
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.
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.
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.
Kernel drops create holes in the capture file that can resemble network loss. Check the final counters before interpreting missing sequence ranges or responses.
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.
A filter can remove causal traffic:
tcp port 443 excludes the preceding DNS exchange.dst port 443 excludes server replies.Start from the observable question and include the protocols needed to explain both success and failure.
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.
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.
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.
5 quizzes