NETWORK-L1 Supplemental 64: tcpdump Complete Guide: Capturing at Command Line

Supplemental 64: tcpdump Complete Guide: Capturing at Command Line
Author: Patrick Luan de Mattos
Category: network-l1
Level: Intermediate
Generated: 2026-04-22T15:35:55.735Z
Supplemental Chapter: Serial 64
tcpdump Complete Guide: Capturing at the Command Line
Focus: BPF Syntax, Protocol Filters, Interface Selection, PCAP Write, Flow Following
Level: Intermediate
Introduction: Unveiling Network Secrets with tcpdump
In the intricate world of networking, understanding the flow of data is paramount. Whether you're troubleshooting a stubborn connectivity issue, analyzing potential security threats, or simply seeking to deepen your comprehension of network protocols, the ability to capture and inspect live network traffic is an invaluable skill. Among the most powerful and ubiquitous tools for this purpose is tcpdump. This command-line utility, available on virtually all Unix-like systems, provides an unparalleled window into the packets traversing your network interfaces.
This chapter serves as your comprehensive guide to mastering tcpdump. We will delve deep into its capabilities, from the fundamental art of selecting the right network interface to the sophisticated techniques of filtering traffic with Berkeley Packet Filter (BPF) syntax. You'll learn how to write captured data to PCAP files for later analysis, how to follow specific network flows, and how to leverage tcpdump for proactive security monitoring. For cybersecurity professionals, tcpdump is an indispensable tool for identifying suspicious activity, understanding the behavior of potential exploits, and even reverse-engineering network-based attacks. While discussions around emerging vulnerabilities and advanced hardware like the Apple M3 neural engine often capture headlines, the foundational ability to analyze network traffic with tools like tcpdump remains critical for dissecting and responding to real-world security challenges. We will also touch upon how the principles of packet analysis are fundamental to understanding the impact of various CVEs, from those affecting AI models to those impacting core infrastructure.
1. The Art of Interface Selection: Where is the Traffic Flowing?
Before you can capture any traffic, you must tell tcpdump which network interface to listen on. Network interfaces are the physical or virtual pathways through which your system communicates with the network. Common examples include Ethernet adapters (eth0, en0), wireless interfaces (wlan0), and loopback interfaces (lo).
1.1 Identifying Available Interfaces
The first step is to discover the interfaces present on your system. You can do this using the tcpdump command itself with the -D option:
tcpdump -DExample Output:
1.eth0 [Up, Running, Connected, Broadcast, Multicast, Up]
2.wlan0 [Up, Running, Connected, Broadcast, Multicast, Up]
3.lo [Up, Running, Broadcast, Multicast, Up]
4.any (Pseudo-interface, supports data link types: Ethernet, PPP, Token Ring, Frame Relay, ATM, HDLC, Cisco HDLC, POSIX, LINUX_SLL)The output lists the available interfaces along with their status. The any pseudo-interface is a special case that can capture traffic from all supported protocols on all interfaces simultaneously, though it can sometimes lead to duplicate packets and might not be supported by all tcpdump versions or operating systems.
1.2 Specifying the Interface with -i
Once you've identified the interface you're interested in, you use the -i option followed by the interface name.
Example: Capturing traffic on the eth0 interface:
tcpdump -i eth0Example: Capturing traffic on the wlan0 interface:
tcpdump -i wlan0Example: Capturing traffic on the loopback interface (useful for analyzing local inter-process communication):
tcpdump -i loSecurity Note: Capturing traffic on interfaces that are not directly managed by you, especially in shared or public network environments, can have privacy implications. Always ensure you have the necessary permissions and are aware of the potential data you are collecting.
2. Mastering BPF Syntax: The Power of Packet Filtering
tcpdump's true power lies in its ability to filter packets before they are displayed or saved. This is achieved through the use of Berkeley Packet Filter (BPF) syntax. BPF allows you to specify complex criteria for selecting packets based on various attributes, including source/destination IP addresses, ports, protocols, and even packet content.
BPF filters are structured as a series of primitives. A primitive consists of an expression (e.g., host, port, proto) and an optional qualifier (e.g., src, dst, tcp, udp). Primitives can be combined using logical operators (and, or, not).
2.1 Basic Primitives
host <ip_address>: Matches packets where either the source or destination IP address is<ip_address>.src host <ip_address>: Matches packets where the source IP address is<ip_address>.dst host <ip_address>: Matches packets where the destination IP address is<ip_address>.net <network_address>: Matches packets on a specific network (e.g.,net 192.168.1.0/24).port <port_number>: Matches packets where either the source or destination port is<port_number>.src port <port_number>: Matches packets where the source port is<port_number>.dst port <port_number>: Matches packets where the destination port is<port_number>.proto <protocol_name>: Matches packets of a specific protocol. Common protocols includetcp,udp,icmp,arp,ip,ip6,ether.
2.2 Combining Primitives with Logical Operators
and(or&&): Both conditions must be true.or(or||): At least one condition must be true.not(or!): Negates the condition.
2.3 Protocol Filters in Action
Let's explore some practical examples of BPF filters.
Example: Capture all traffic to or from a specific IP address:
tcpdump -i eth0 host 192.168.1.100Example: Capture all HTTP traffic (port 80):
tcpdump -i eth0 port 80Example: Capture all SSH traffic (port 22) to a specific server:
tcpdump -i eth0 dst host 192.168.1.50 and dst port 22Example: Capture all DNS traffic (UDP port 53):
tcpdump -i eth0 udp port 53This is particularly useful for debugging DNS resolution issues, which often rely on the specifications outlined in RFC 1035 and RFC 1034. Understanding these RFCs is key to diagnosing why DNS queries might be failing.
Example: Capture all ICMP traffic (ping requests/replies):
tcpdump -i eth0 icmpExample: Capture traffic not to a specific IP address:
tcpdump -i eth0 not host 192.168.1.1Example: Capture TCP traffic from a specific IP and port:
tcpdump -i eth0 src host 192.168.1.200 and src port 12345Example: Capture traffic to a specific network:
tcpdump -i eth0 net 192.168.2.0/24Example: Capture all Ethernet traffic (Layer 2):
tcpdump -i eth0 etherThis can be useful for inspecting ARP requests/replies, as described in RFC ARP.
Example: Capture traffic related to a specific CVE (hypothetical scenario):
While tcpdump doesn't directly filter by CVE, you can often infer traffic patterns associated with a vulnerability by analyzing known exploit techniques. For instance, if a CVE-2026-5281 exploit targets a specific port or protocol, you could filter for that. If the exploit involves sending malformed data, you might look for unusual packet sizes or content patterns.
Example: Capturing traffic that might be related to a "zerosday" (zero-day) exploit:
Zero-day exploits are particularly challenging as they are unknown to vendors. However, tcpdump can still be your first line of defense. By capturing all unusual or unexpected traffic patterns on your network, you can later analyze them for anomalies that might indicate a zero-day in progress. This often involves looking for traffic to or from unknown IP addresses, unexpected protocol usage, or unusually high volumes of traffic.
Example: Capturing traffic that might be associated with a potential "anthropic code leak" or "anthropic claude code vulnerability":
If there were a hypothetical leak of Anthropic's Claude code, and it revealed a network-related vulnerability, tcpdump would be crucial for observing any traffic patterns that exploit it. This might involve unusual API calls, unexpected data exfiltration, or specific patterns of communication that deviate from normal AI model interaction. The ability to precisely filter traffic based on protocol and IP addresses allows security analysts to isolate and examine these specific communication channels.
2.4 Advanced BPF Features
protochain <protocol>: Matches packets that are part of a protocol chain. For example,tcpdump 'tcp port 80'will only show TCP packets.tcpdump 'tcp port 80 and ip'will also show TCP packets, but theipqualifier is redundant here.protochainis more useful for layered protocols.len <length>: Matches packets of a specific length.greater <length>/less <length>: Matches packets greater than or less than a specific length.and proto[offset:size] = value: This is a powerful feature that allows you to inspect specific bytes within packet headers or payload.offset: The byte offset from the beginning of the protocol header.size: The number of bytes to examine (e.g.,1for a byte,2for a short,4for a long).value: The hexadecimal or decimal value to match.
Example: Capturing ICMP packets with a specific type and code (e.g., Type 8, Code 0 for Echo Request):
tcpdump -i eth0 icmp[0:1] = 8 and icmp[1:1] = 0Here, icmp[0:1] refers to the first byte (type) of the ICMP header, and icmp[1:1] refers to the second byte (code).
Example: Capturing TCP packets with the SYN flag set:
tcpdump -i eth0 'tcp[tcpflags] & 0x02 != 0'Here, tcp[tcpflags] refers to the TCP flags byte. 0x02 is the hexadecimal representation of the SYN flag. The & performs a bitwise AND operation, and != 0 checks if the SYN flag is set.
Example: Capturing UDP packets with a specific destination port (e.g., 53 for DNS):
tcpdump -i eth0 'udp[4:2] = 53'Here, udp[4:2] refers to the two bytes representing the destination port, which starts at offset 4 in the UDP header.
Example: Capturing packets containing a specific string (case-sensitive):
tcpdump -i eth0 'tcp port 80 and tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x47455420' # For HTTP GETThis example is more advanced. It decodes the TCP header to find the data offset (tcp[12:1] & 0xf0) >> 2), then looks for the ASCII bytes representing "GET " (0x47455420).
2.5 Using tcpdump with Python and Scapy
For more programmatic analysis and complex filtering, the Python scapy library is an excellent complement to tcpdump. scapy can both capture packets and craft them, offering a powerful scripting environment.
from scapy.all import sniff, IP, TCP, UDP, ICMP
# Filter for TCP traffic on port 80
def filter_http(packet):
if packet.haslayer(TCP) and packet[TCP].dport == 80:
print(f"HTTP packet captured: {packet.summary()}")
# Filter for DNS traffic
def filter_dns(packet):
if packet.haslayer(UDP) and packet[UDP].dport == 53:
print(f"DNS packet captured: {packet.summary()}")
# Filter for ICMP traffic
def filter_icmp(packet):
if packet.haslayer(ICMP):
print(f"ICMP packet captured: {packet.summary()}")
# Capture and filter
print("Capturing HTTP traffic...")
sniff(iface="eth0", prn=filter_http, filter="tcp port 80", count=10)
print("\nCapturing DNS traffic...")
sniff(iface="eth0", prn=filter_dns, filter="udp port 53", count=10)
print("\nCapturing ICMP traffic...")
sniff(iface="eth0", prn=filter_icmp, filter="icmp", count=10)This Python script demonstrates how to use scapy's sniff function with BPF filters. prn specifies a callback function to execute for each captured packet, and filter applies the BPF expression.
3. Writing PCAP Files: Preserving Network Evidence
While tcpdump can display packets in real-time, it's often more practical to save them to a file for later, in-depth analysis. This is where the -w option comes in. The captured packets are saved in the pcap (packet capture) format, which is a standard widely used by network analysis tools like Wireshark.
3.1 Saving Captures to a File
The -w option is followed by the desired filename.
Example: Capture all traffic on eth0 and save it to capture.pcap:
tcpdump -i eth0 -w capture.pcapExample: Capture only HTTP traffic and save it to http_traffic.pcap:
tcpdump -i eth0 port 80 -w http_traffic.pcapExample: Capture traffic to/from a specific IP and save it:
tcpdump -i eth0 host 192.168.1.100 -w host_traffic.pcap3.2 Reading from a PCAP File with -r
Once you have a .pcap file, you can use tcpdump to read and display its contents using the -r option. This is incredibly useful for offline analysis, forensics, and replaying network scenarios.
Example: Read and display the contents of capture.pcap:
tcpdump -r capture.pcapExample: Read capture.pcap and apply a filter:
tcpdump -r capture.pcap host 192.168.1.100This allows you to re-filter previously captured data without needing to recapture it.
Example: Read http_traffic.pcap and display it with more verbosity:
tcpdump -r http_traffic.pcap -v3.3 PCAP File Management and Security
- File Size: PCAP files can grow very large, especially on busy networks. Use filters effectively to capture only what you need.
- Permissions: Ensure that the user running
tcpdumphas write permissions to the directory where you are saving the PCAP files. - Storage: Plan for sufficient disk space, especially for long-duration captures.
- Integrity: PCAP files are valuable forensic evidence. Ensure they are stored securely and their integrity is maintained.
4. Following Network Flows: Tracing a Conversation
Sometimes, simply looking at individual packets isn't enough. You need to understand the entire conversation between two endpoints. tcpdump offers ways to highlight and follow specific network flows.
4.1 Verbosity Levels (-v, -vv, -vvv)
The -v (verbose), -vv (more verbose), and -vvv (most verbose) options increase the amount of detail tcpdump displays for each packet. This can help in understanding the context of individual packets within a flow.
Example: Verbose output for SSH traffic:
tcpdump -i eth0 -vvv tcp port 224.2 The -A Option: ASCII Payload Display
The -A option displays the packet payload in ASCII. This is incredibly useful for inspecting the actual data being transmitted, especially for protocols like HTTP, SMTP, or FTP where human-readable content is common.
Example: Display HTTP traffic in ASCII:
tcpdump -i eth0 -A port 80This can reveal sensitive information being transmitted in plain text, a critical security consideration.
4.3 Combining Filters for Flow Analysis
By combining filters, you can isolate specific conversations.
Example: Capture all traffic between two specific IPs:
tcpdump -i eth0 host 192.168.1.100 and host 192.168.1.200Example: Capture all TCP traffic for a specific connection (source IP, source port, destination IP, destination port):
tcpdump -i eth0 src 192.168.1.100 and src port 54321 and dst 192.168.1.200 and dst port 804.4 Using Wireshark for Flow Following
While tcpdump is excellent for capturing and initial filtering, its flow-following capabilities are limited compared to graphical tools. For deep flow analysis, saving to a PCAP file and then opening it in Wireshark is highly recommended. Wireshark's "Follow TCP Stream" or "Follow UDP Stream" features provide an unparalleled view of a complete conversation.
5. tcpdump for Network Security Analysis
tcpdump is a cornerstone tool for network security professionals. It enables proactive monitoring, incident response, and forensic analysis.
5.1 Detecting Suspicious Activity
- Unusual Port Usage: Monitor for traffic on non-standard ports, which could indicate covert channels or malware.
tcpdump -i eth0 'not (port 22 or port 80 or port 443 or port 53)' - Excessive ICMP Traffic: An unusual volume of ICMP packets might indicate a denial-of-service (DoS) attack or network scanning.
tcpdump -i eth0 icmp -c 1000 # Capture first 1000 ICMP packets - Connection Attempts to Unknown IPs: Monitor for connections to or from IP addresses not present in your known network.
tcpdump -i eth0 'not net 192.168.1.0/24' # Assuming 192.168.1.0/24 is your local network - Suspicious Payload Content: Use
-Ato inspect data for keywords or patterns indicative of malicious activity. This is crucial when investigating potential breaches or analyzing the behavior of malware.
5.2 Analyzing Exploits and Vulnerabilities
When a new CVE is announced, tcpdump becomes vital for understanding its network impact.
- Replicating Exploit Traffic: If a PoC (Proof of Concept) for a vulnerability like CVE-2026-5281 is available, you can use
tcpdumpto capture the traffic generated by the exploit. This helps in understanding the exact packets and payloads used. - Identifying Exploitation Patterns: By filtering for specific ports or protocols targeted by a known exploit (e.g., CVE-2026-34040 poc, CVE-2026-20963 github), you can monitor your network for signs of attempted exploitation.
- Zero-Day Detection: As mentioned earlier, capturing all traffic and looking for anomalies is the primary strategy for detecting zerosday threats before they are publicly known. This requires a keen eye for deviations from normal network behavior.
5.3 Incident Response
In the event of a security incident, tcpdump is used to:
- Capture live traffic from affected systems or network segments.
- Save forensic evidence to PCAP files for later, detailed analysis.
- Identify the source and destination of malicious traffic.
- Understand the attack vector and the extent of the compromise.
5.4 Understanding Protocol Standards
tcpdump is an excellent tool for learning and verifying protocol implementations. For example, examining DNS traffic can help solidify understanding of RFC 1035 and RFC 1034. Analyzing ARP packets aids in understanding RFC ARP.
5.5 Blocking Malicious Outbound Connections
While tcpdump itself doesn't block traffic, the insights gained from it can inform firewall rules. For instance, if you observe malicious outbound connections from a process like mshta.exe, you can use this information to block outbound network connections from Microsoft HTML Application Host (mshta.exe) using host-based firewalls or network access control lists (ACLs).
6. tcpdump Options for Enhanced Control
Beyond the core functionalities, tcpdump offers numerous options to fine-tune your captures.
-n: Don't resolve hostnames or port numbers. This speeds up capture and can be useful if DNS is unreliable or being targeted.-nn: Don't resolve hostnames, port numbers, or protocol names.-X: Print each packet in hex and ASCII.-XX: Print each packet in hex and ASCII, including the link-level header.-c <count>: Exit after capturing<count>packets.-s <snaplen>: Set the snapshot length (the number of bytes to capture from each packet).0means capture the entire packet.-E <keyfile>: Decrypt IPsec encrypted packets using the specified key file.-Z <user>: Change the user ID of thetcpdumpprocess after opening the capture device. This can be useful for security reasons, runningtcpdumpas a less privileged user after initial setup.
Example: Capture full packets (not truncated) for 100 packets, showing hex and ASCII:
tcpdump -i eth0 -s 0 -c 100 -XX7. Troubleshooting with tcpdump
tcpdump is an indispensable tool for diagnosing a wide range of network problems.
7.1 Connectivity Issues
- Is the traffic reaching the destination? Filter for traffic to/from the destination IP and port. If you don't see it, the problem is likely upstream.
- Is the destination responding? Filter for traffic from the destination IP. If you don't see responses, the destination might be down, overloaded, or blocking your traffic.
- Are there any firewall rules blocking traffic? Observe if SYN packets are sent but no SYN-ACK is received. This often indicates a firewall dropping the traffic.
7.2 Performance Problems
- High Latency: Observe the timestamps of packets in a conversation. Large gaps between requests and responses indicate latency.
- Packet Loss: If you see retransmissions in TCP traffic (indicated by sequence numbers), it suggests packet loss.
- Bandwidth Saturation: Monitor the volume of traffic on an interface to identify potential bottlenecks.
7.3 Application-Specific Issues
- DNS Resolution Failures: Capture UDP port 53 traffic to see if DNS queries are being sent and if valid responses are received.
- Web Server Issues: Capture TCP port 80/443 traffic to examine HTTP requests and responses.
8. tcpdump and Advanced Hardware/Architectures
While tcpdump is a general-purpose tool, understanding its interaction with advanced hardware and architectures is important.
- Hardware Offloading: Modern network interface cards (NICs) can offload certain tasks (like checksum calculation) from the CPU.
tcpdumptypically captures packets after they've been processed by the NIC, so you're seeing the "effective" packets on the wire. - Virtualization: In virtualized environments (e.g., VMware, KVM),
tcpdumpcan capture traffic on virtual interfaces (e.g.,vethin Linux containers,vmnetin VMs). - Embedded Systems:
tcpdumpis often found on embedded devices, providing crucial insights into their network behavior, which can be relevant when analyzing vulnerabilities in specialized hardware or firmware.
Conclusion: Your Command-Line Network Detective
tcpdump is more than just a packet sniffer; it's a powerful diagnostic and analytical tool that empowers you to understand the inner workings of your network. By mastering its interface selection, BPF syntax, PCAP writing capabilities, and flow-following techniques, you gain the ability to troubleshoot complex issues, uncover security threats, and deepen your understanding of network protocols. Whether you're a seasoned network engineer, a cybersecurity analyst, or a student of networking, tcpdump should be a fundamental part of your toolkit. Its command-line nature makes it incredibly versatile, allowing for automation and integration into scripts, making it an enduringly relevant tool in the ever-evolving landscape of network technology.
Exercises
- Identify Your Interfaces: Run
tcpdump -Don your system and list all available network interfaces. - Basic Capture: Capture the first 20 packets on your primary network interface and display them.
- HTTP Traffic: Capture all HTTP traffic (port 80) on your system and save it to a file named
http_capture.pcap. - DNS Traffic Analysis: Capture and display (without saving) the first 10 DNS queries (UDP port 53) originating from your system.
- Specific Host Traffic: Capture all traffic to and from the IP address
8.8.8.8for 30 seconds and save it togoogle_dns.pcap. - SSH and HTTP Combined: Capture traffic that is either SSH (port 22) or HTTP (port 80) on your primary interface and display it.
- No Localhost Traffic: Capture all traffic on your primary interface except traffic to or from
127.0.0.1(localhost). - TCP SYN Flags: Capture and display the first 5 TCP packets on your interface that have the SYN flag set.
- Read and Filter PCAP: Using the
google_dns.pcapfile created in Exercise 5, read its contents and then filter to show only packets originating from8.8.8.8. - ASCII Payload Inspection: Capture 10 packets of HTTP traffic (port 80) and display their payloads in ASCII using the
-Aoption. Examine the output for any recognizable HTTP headers or content. - Advanced Filter - Specific ICMP Type: Capture and display ICMP packets with a Type of 3 (Destination Unreachable). (Hint:
icmp[0:1] = 3) - Capture Full Packets: Capture the first 5 packets on your interface, ensuring that the entire packet is captured (not truncated), and display them in hex and ASCII format.
This chapter is part of the "From Zero to Network Doctor" open textbook series. All examples are educational and use safe, lab-only environments.
