Tcpdump And Command Line Capture
Category: Network Tools and Commands
Type: Network Tools & Commands
Generated on: 2025-07-10 09:15:45
For: Network Engineering, Administration & Technical Interviews
This cheatsheet covers tcpdump and related command-line tools for network packet capture and analysis. It focuses on practical examples and common use cases for network administrators and engineers.
1. Tool Overview
tcpdump: A powerful command-line packet analyzer that captures and displays network traffic matching specified criteria. Essential for troubleshooting network issues, security analysis, and protocol debugging.tshark: (Included in Wireshark) A command-line packet analyzer that provides similar functionality to Wireshark but without the GUI. Useful for automated packet capture and analysis in scripts.tcpflow: Reconstructs TCP streams from packet captures, making it easier to analyze application-level data.
When to Use:
- Troubleshooting network connectivity issues (e.g., dropped packets, slow performance).
- Analyzing network protocols (e.g., HTTP, DNS, SMTP).
- Debugging application communication problems.
- Security monitoring and intrusion detection.
- Capturing traffic for later analysis with Wireshark.
- Verifying network configuration changes.
2. Basic Syntax
tcpdump:
tcpdump [options] [expression]tshark:
tshark [options] [filter]tcpflow:
tcpflow [options] [expression]options: Flags that modify the behavior of the tool (e.g., interface, verbosity).expression(tcpdump, tcpflow): A filter expression that specifies which packets to capture or analyze. Uses a Berkeley Packet Filter (BPF) syntax.filter(tshark): A display filter similar to Wireshark’s filter syntax.
3. Practical Examples
tcpdump
-
Capture all traffic on the default interface:
Terminal window sudo tcpdumpSample Output:
14:32:28.123456 IP 192.168.1.100.53456 > 8.8.8.8.53: Flags [S], seq 1234567890, win 65535, options [mss 1460,sackOK,TS val 123456789 ecr 0,nop,wscale 7], length 014:32:28.123567 IP 8.8.8.8.53 > 192.168.1.100.53456: Flags [S.], seq 987654321, ack 1234567891, win 65535, options [mss 1460,sackOK,TS val 123456789 ecr 123456789,nop,wscale 7], length 014:32:28.123678 IP 192.168.1.100.53456 > 8.8.8.8.53: Flags [.], ack 987654322, win 65535, TS val 123456790 ecr 123456789, length 0 -
Capture traffic on a specific interface (
eth0):Terminal window sudo tcpdump -i eth0 -
Capture traffic to or from a specific host (192.168.1.100):
Terminal window sudo tcpdump host 192.168.1.100 -
Capture traffic to or from a specific port (80):
Terminal window sudo tcpdump port 80 -
Capture HTTP traffic:
Terminal window sudo tcpdump port 80 or port 443 -
Capture TCP traffic with the SYN flag set (to detect new connections):
Terminal window sudo tcpdump 'tcp[tcpflags] & tcp-syn != 0' -
Capture traffic and save it to a file (
capture.pcap):Terminal window sudo tcpdump -w capture.pcap -
Read a capture file:
Terminal window tcpdump -r capture.pcap
tshark
-
Capture traffic and filter for HTTP requests:
Terminal window sudo tshark -i eth0 -Y "http.request" -
Capture traffic and display only the HTTP request URI:
Terminal window sudo tshark -i eth0 -Y "http.request" -T fields -e http.request.uri -
Read a capture file and filter for DNS queries:
Terminal window tshark -r capture.pcap -Y "dns.flags.response == 0"
tcpflow
-
Capture traffic on eth0, outputting each TCP stream to a separate file in the current directory:
Terminal window sudo tcpflow -i eth0- This will create files named like
192.168.1.100.53456-8.8.8.8.53containing the reconstructed TCP stream.
- This will create files named like
-
Analyze a capture file:
Terminal window tcpflow -r capture.pcap -
Filter for specific host and port:
Terminal window tcpflow -r capture.pcap "host 192.168.1.100 and port 80"
4. Common Options
tcpdump
-i <interface>: Specify the interface to listen on (e.g.,eth0,wlan0,any).anycaptures on all interfaces.-n: Don’t resolve hostnames. Speeds up capture and avoids DNS lookups.-nn: Don’t resolve hostnames or port numbers.-v: Verbose output.-vv: More verbose output.-vvv: Most verbose output.-w <file>: Write the raw packets to a file for later analysis.-r <file>: Read packets from a file.-c <count>: Capture only<count>number of packets.-s <snaplen>: Set the snapshot length (the number of bytes to capture from each packet).-s 0captures the entire packet.-A: Print each packet (minus its link level header) in ASCII. Handy for viewing HTTP content.-X: Print each packet (minus its link level header) in hex and ASCII.-XX: Print each packet, including link level header, in hex and ASCII.-q: Less verbose output (quiet).-t: Don’t print a timestamp on each dump line.-ttt: Print a delta (microsecond resolution) between current and previous line.-tttt: Print a delta (microsecond resolution) between current and first line.-T <type>: Interpret raw packets as being of the specified type (e.g.,vlan,mpls).
tshark
-i <interface>: Specify the interface to listen on.-r <file>: Read packets from a file.-w <file>: Write the raw packets to a file.-Y <filter>: Apply a display filter.-T <pdml|psml|text|fields|json>: Output format (default is text).-e <field>: Specify a field to output when using-T fields.-n: Disable network object name resolution (e.g., hostnames, port names).-N <option>: Control name resolution behavior (e.g.,mfor MAC addresses,vfor VLAN IDs).-c <count>: Capture only<count>number of packets.-f <capture filter>: Set a capture filter (BPF syntax, liketcpdump). Use for capturing only the packets you need. Better for performance than-Y.
tcpflow
-i <interface>: Specify the interface to listen on.-r <file>: Read packets from a file.-c: Do not discard packets with checksum errors.-a: All: save the data from all flows. Normally, only TCP flows are saved.-e <engine>: Select the pattern matching engine to use (e.g., “grep”, “pcre”).-v: Verbose output.-o <outputdir>: Specify the output directory. Defaults to current directory.
5. Advanced Usage
tcpdump
-
Capture traffic to a specific subnet (192.168.1.0/24):
Terminal window sudo tcpdump net 192.168.1.0/24 -
Capture traffic based on packet size (greater than 1000 bytes):
Terminal window sudo tcpdump 'greater 1000' -
Capture fragmented IP packets:
Terminal window sudo tcpdump 'ip[6:2] & 0x1fff != 0' -
Capture traffic with a specific TCP flag combination (SYN-ACK):
Terminal window sudo tcpdump 'tcp[tcpflags] & (tcp-syn|tcp-ack) == (tcp-syn|tcp-ack)' -
Rotating Capture Files: Capture to multiple files with a maximum size, and rotate them.
Terminal window sudo tcpdump -w capture.pcap -C 100 -W 5 # Create 5 files, each 100MB in size
tshark
-
Capture traffic and extract specific fields to CSV:
Terminal window sudo tshark -i eth0 -T fields -e frame.number -e ip.src -e ip.dst -e tcp.srcport -e tcp.dstport -e http.request.uri -E separator=, -E quote=d -E occurrence=f > output.csv -
Capture traffic and display only the first HTTP request:
Terminal window sudo tshark -c 1 -Y "http.request" -
Use capture filters and display filters together: Capture only TCP traffic on port 80, but then display only HTTP GET requests. This is more efficient than using only a display filter.
Terminal window sudo tshark -i eth0 -f "tcp port 80" -Y "http.request.method == \"GET\""
tcpflow
-
Use
tcpflowwith grep to search for specific patterns within the reconstructed streams:Terminal window tcpflow -r capture.pcap | grep "User-Agent" -
Filter by payload size: (This is an example using
tcpdumpto capture, thentcpflowto reconstruct, but the filtering is done based ontcpdump’s capabilities.)Terminal window sudo tcpdump -i eth0 "len > 1000" -w capture.pcap && tcpflow -r capture.pcap
6. Troubleshooting Scenarios
-
Problem: Cannot connect to a specific website.
Terminal window # Check DNS resolutiontcpdump -n port 53# Check TCP handshaketcpdump -n -i eth0 host <website_ip> and port 80 or port 443# Check for routing issuestraceroute <website_ip> -
Problem: Slow network performance.
Terminal window # Identify top talkerstcpdump -n -i eth0 | awk '{print $3}' | sort | uniq -c | sort -nr | head -10# Check for retransmissionstcpdump -n -i eth0 'tcp.analysis.retransmission'# Check for TCP window size issuestcpdump -n -i eth0 'tcp.window_size == 0' -
Problem: Application communication failing.
Terminal window # Capture traffic between the application serverstcpdump -n -i eth0 host <server1_ip> and host <server2_ip> and port <application_port># Use tcpflow to reconstruct the application streamstcpflow -r capture.pcap
7. Output Interpretation
tcpdump
- Timestamp: Date and time of the packet capture.
- Protocol: Network protocol (e.g., IP, TCP, UDP).
- Source: Source IP address and port.
- Destination: Destination IP address and port.
- Flags: TCP flags (e.g., SYN, ACK, FIN, RST, PSH, URG).
- Sequence Number: TCP sequence number.
- Acknowledgement Number: TCP acknowledgement number.
- Window Size: TCP window size.
- Options: TCP options (e.g., MSS, SACK, Timestamp).
- Length: Packet length.
tshark
tshark’s output depends on the options used. It can range from a summary of each packet to a detailed breakdown of each protocol layer. The-T fieldsoption allows for extracting specific data points.
tcpflow
tcpflowreconstructs TCP streams and saves them to files. The filenames indicate the source and destination IP addresses and ports. The content of the files is the application-level data exchanged during the TCP session.
8. Security Considerations
- Capture Sensitive Data: Packet captures can contain sensitive information (e.g., passwords, credit card numbers). Store capture files securely and restrict access.
- Performance Impact: Capturing traffic can consume significant system resources, especially on high-traffic networks. Use filters to capture only the necessary traffic.
- Root Privileges:
tcpdumpandtsharkoften require root privileges to capture traffic on network interfaces. Usesudoor configure appropriate permissions. - Legal Issues: Capturing network traffic may be subject to legal restrictions. Consult with legal counsel before capturing traffic on a production network.
- Avoid Capturing on Public Networks: Capturing traffic on public networks can expose you to security risks.
9. Platform Differences
- Linux:
tcpdumpis usually pre-installed.tsharkandtcpfloware available through package managers (e.g.,apt,yum). - Windows:
tcpdumpis available through WinPcap/Npcap.tsharkis included in the Wireshark installation.tcpflowis available from various sources; ensure you download from a reputable site. You may need to run as Administrator. - macOS:
tcpdumpis usually pre-installed.tsharkis included in the Wireshark installation.tcpflowis available through package managers like Homebrew. You may need to usesudo.
Example Platform-Specific Command (macOS):
sudo tcpdump -i en0 host 192.168.1.100 # 'en0' is a common Wi-Fi interface on macOSImportant Notes:
- Always use the most specific filter possible to reduce the amount of data captured and improve performance.
- Test your filters in a lab environment before deploying them to a production network.
- Be aware of the legal and ethical implications of capturing network traffic.
- Always use
sudowhen required on Linux and macOS. - Consider using a GUI-based packet analyzer like Wireshark for more complex analysis.
tcpdumpandtsharkare often used to capture the initial data, which is then analyzed in Wireshark. - Regularly update your packet capture tools to ensure you have the latest security patches and features.