VMware ESXi and vSphere Cluster Management
How to Intercept and Log Network Packets in Linux with tcpdump
Learn how to use tcpdump on Linux to capture, filter, inspect, save, rotate, and review network packets safely for troubleshooting and forensic analysis.
tcpdump is a command-line utility for capturing and examining network packets on Linux and other Unix-like systems. It uses the libpcap capture library, can display packet summaries, applies Berkeley Packet Filter (BPF) expressions, and writes captures to files for later analysis.
This lesson covers interface selection, privileges, live capture, readable output, BPF filters, pcap files, rotation, encrypted traffic, and safe forensic handling. You should already understand basic Linux commands, sudo, IP addresses, subnets, ports, TCP, UDP, ICMP, DNS, and file permissions.
Why Capture Network Packets?
A packet capture is the collection of network frames or packets observed on a network interface. Capturing does not mean that a host can automatically see every packet on a network; visibility depends on the interface, network topology, routing, switching, and capture location.
Authorized packet capture is useful for:
- Diagnosing connectivity, routing, retransmission, and latency problems.
- Debugging application protocols and confirming whether requests and responses are exchanged.
- Responding to security incidents and investigating suspicious communication.
- Creating traffic baselines for normal network behavior.
- Collecting evidence for a digital forensic investigation.
Install and Verify tcpdump
Check whether the program is installed and identify its version:
tcpdump --version
command -v tcpdumpInstall it using the package manager for your distribution:
sudo apt update && sudo apt install tcpdump
sudo dnf install tcpdump
sudo yum install tcpdump
sudo pacman -S tcpdump
sudo zypper install tcpdumpUse the command appropriate for Debian or Ubuntu, RHEL or Fedora-family systems, Arch-based systems, or SUSE. Package names, default permissions, and security policies can differ between distributions.
Privileges and Capture Permissions
Opening a capture device commonly requires root privileges or suitable Linux capabilities. At a conceptual level, CAP_NET_RAW permits certain raw-network operations and CAP_NET_ADMIN permits some network administration operations. The exact requirements depend on the distribution, capture method, interface, and security policy.
For a short, authorized task, use sudo rather than running an entire shell as root:
sudo tcpdump -i eth0 -nn -c 20Do not broadly grant capabilities or set elevated privileges just for convenience. If a service, container, or restricted environment cannot open the interface, review its approved privilege model, sandbox, namespace, and local security controls.
Select a Network Interface
A network interface is a physical or virtual connection through which a host sends and receives traffic. Common examples include Ethernet devices such as eth0, Wi-Fi devices such as wlan0, the loopback interface lo, bridges, VPN adapters, VLAN devices, and container or network-namespace interfaces.
List interfaces recognized by tcpdump and inspect Linux link information:
sudo tcpdump -D
ip link showThe -D output may include an any pseudo-interface. Capturing on any can help when traffic may use Ethernet, loopback, a VPN, a bridge, or a container interface, but it combines traffic from multiple interfaces and can make direction, link-layer headers, and duplicate observations harder to interpret. Prefer one known interface when the scope is clear.
Basic Live Capture
Capture continuously from a selected interface:
sudo tcpdump -i eth0For a controlled test, stop after 20 packets and avoid name lookups:
sudo tcpdump -i eth0 -nn -c 20Press Ctrl+C to stop an unbounded capture cleanly. tcpdump reports capture statistics when it exits. Generate a known test, such as an authorized ping or DNS lookup, rather than collecting indefinitely.
Typical default output contains a timestamp, source endpoint, destination endpoint, protocol or transport information, ports, TCP flags where applicable, and a short packet summary. For example, a TCP line can show a source address and source port sending to a destination address and destination port, followed by flags such as [S] for SYN or [S.] for SYN plus acknowledgment.
Readable Output and Packet Detail
tcpdump may perform DNS resolution, which converts addresses into host names. It may also translate port numbers into service names. These lookups can add delay and make output less predictable. Use -n for numeric addresses, -nn for numeric addresses and ports, and -nn is usually the clearest choice for troubleshooting.
| Option | Purpose | Example use | Operational note |
|---|---|---|---|
-D | List capture-capable interfaces | tcpdump -D | Use before assuming a device name. |
-i | Select an interface | -i eth0 | Choose the interface carrying the target traffic. |
-c | Stop after a packet count | -c 20 | Useful for bounded tests. |
-n | Do not resolve host names | -n | Addresses remain numeric. |
-nn | Do not resolve host names or service names | -nn | Reduces lookup delay and ambiguity. |
-v, -vv, -vvv | Increase decoding verbosity | -vv | More detail also means more clutter. |
-e | Show link-layer headers | -e | Useful for MAC addresses and VLAN-related context. |
-A | Show printable payload as ASCII | -A 'tcp port 80' | May expose credentials or sensitive content. |
-X | Show payload in hexadecimal and ASCII | -X 'udp port 53' | Useful for protocol inspection; protect the output. |
-s | Set snapshot length | -s 128 | A smaller value saves space but can truncate payloads. |
-w | Write a pcap-compatible binary file | -w capture.pcap | Terminal output is not a substitute for preserved packets. |
-r | Read a saved capture | -r capture.pcap | Supports repeatable offline analysis. |
-C | Rotate after an approximate file size in megabytes | -C 100 | Combine with -W to cap file count. |
-G | Rotate after a time interval in seconds | -G 300 | Time-based naming works with strftime patterns. |
-W | Limit the number of rotated files | -W 12 | Confirm naming and overwrite behavior for your version. |
-p | Do not request promiscuous mode | -p | Restricts capture to frames normally delivered to the interface. |
Increase detail only when it answers a specific question:
sudo tcpdump -i eth0 -nn -vv
sudo tcpdump -i eth0 -nn -e
sudo tcpdump -i eth0 -nn -A 'tcp port 80'
sudo tcpdump -i eth0 -nn -X 'udp port 53'ASCII and hexadecimal views can reveal application data. Avoid them unless payload inspection is necessary and authorized.
Filter Packets with BPF Expressions
A BPF filter is a Berkeley Packet Filter expression evaluated during capture. Capture-time filtering reduces noise, storage use, processing overhead, and exposure of unrelated traffic. Shell-quote compound expressions so the shell does not interpret parentheses or operators.
| Goal | Filter expression | What it selects |
|---|---|---|
| Traffic involving one host | host 192.0.2.25 | Packets to or from that host. |
| Traffic from one host | src host 192.0.2.25 | Packets whose source is the host. |
| Traffic to one host | dst host 192.0.2.25 | Packets whose destination is the host. |
| Traffic for an IPv4 or IPv6 network | net 192.0.2.0/24 | Traffic involving the specified network; use a suitable IPv6 prefix when needed. |
| TCP traffic | tcp | TCP packets. |
| UDP traffic | udp | UDP packets. |
| ICMP traffic | icmp | IPv4 ICMP packets, such as echo tests. |
| A specific port | port 443 | Traffic using source or destination port 443. |
| A destination port | dst port 443 | Traffic targeting port 443. |
| DNS traffic | udp port 53 or tcp port 53 | Common UDP and TCP DNS traffic. |
| Combined host and port condition | host 192.0.2.25 and tcp port 443 | HTTPS-related TCP traffic involving the host. |
| Excluding SSH administration traffic | not port 22 | Traffic except source or destination port 22. |
Examples:
sudo tcpdump -i eth0 -nn host 192.0.2.25
sudo tcpdump -i eth0 -nn src host 192.0.2.25
sudo tcpdump -i eth0 -nn dst host 192.0.2.25
sudo tcpdump -i eth0 -nn net 192.0.2.0/24
sudo tcpdump -i eth0 -nn tcp
sudo tcpdump -i eth0 -nn udp port 53
sudo tcpdump -i eth0 -nn icmp
sudo tcpdump -i eth0 -nn 'tcp dst port 443'
sudo tcpdump -i eth0 -nn 'host 192.0.2.25 and tcp port 443'
sudo tcpdump -i eth0 -nn '(tcp or udp) and port 53'
sudo tcpdump -i eth0 -nn 'not port 22'Other useful protocol filters include arp, ip for IPv4, and ip6 for IPv6. Port ranges can be expressed with syntax such as portrange 8000-8100. Parentheses make compound conditions unambiguous.
Practical Capture Scenarios
Loopback application traffic
Traffic between processes on the same machine commonly uses lo and never leaves the host:
sudo tcpdump -i lo -nn -c 30HTTP or HTTPS connection attempts
To determine whether a server receives connection attempts on web ports:
sudo tcpdump -i eth0 -nn 'tcp dst port 80 or tcp dst port 443'DNS troubleshooting
Capture both common DNS transports, then inspect summaries or review the file offline:
sudo tcpdump -i eth0 -nn '(udp or tcp) and port 53'
sudo tcpdump -i eth0 -nn -X '(udp or tcp) and port 53'ICMP connectivity testing
sudo tcpdump -i eth0 -nn icmpDuring an authorized ping, look for echo requests and echo replies. A missing reply can indicate routing, filtering, host availability, or return-path problems, but tcpdump alone does not identify the cause.
Save Captures to pcap Files
Terminal output is a human-readable summary. A pcap file is a binary record of captured packets and metadata, preserving substantially more information for later filtering and analysis.
sudo tcpdump -i eth0 -nn -w capture.pcap 'host 192.0.2.25'Use descriptive names containing the host, interface, purpose, and collection time where policy permits. Store files with restrictive permissions, protect them in encrypted storage when required, record hashes when integrity matters, and follow approved retention and deletion rules.
| Characteristic | Terminal output | pcap file |
|---|---|---|
| Primary purpose | Immediate observation | Collection and later analysis |
| Level of retained detail | Mostly decoded summaries | Captured packet records up to the snapshot length |
| Search and repeatability | Limited to what was displayed | Filters and views can be repeated |
| Suitability for forensic preservation | Low | Higher, when properly documented and protected |
| Storage considerations | Uses terminal or redirected text output | Can grow rapidly and requires capacity planning |
| Use with Wireshark | Not directly useful as a packet dataset | Can be opened by compatible packet-analysis tools such as Wireshark |
Read and Review a Saved Capture
Read a pcap without opening a live capture device:
tcpdump -nn -r capture.pcap
tcpdump -nn -r capture.pcap 'tcp port 443'Offline review is safer and repeatable: acquire a narrowly scoped file once, preserve the original, and apply different filters to a working copy. This avoids repeatedly collecting production traffic while exploring a question.
Bound Capture Duration and Storage
Use -c for a packet limit. For a time limit, use an approved shell procedure such as a controlled timeout, or use time-based rotation with -G. A snapshot length controls the maximum bytes retained per packet:
sudo tcpdump -i eth0 -nn -s 128 -w headers-only.pcapA smaller snapshot can reduce storage and payload exposure, but it may remove application data needed for analysis. Choose it deliberately.
Rotate files by time or approximate size and limit the retained count:
sudo tcpdump -i eth0 -nn -w 'capture-%Y%m%d%H%M%S.pcap' -G 300 -W 12
sudo tcpdump -i eth0 -nn -w capture.pcap -C 100 -W 10At high traffic rates, monitor free space, estimate the capture rate, use a restrictive BPF filter, and avoid unbounded collection. Confirm the exact rotation naming and overwrite behavior on the installed tcpdump version before using it in an investigation.
Promiscuous Mode and Network Visibility
Promiscuous mode permits an interface to receive frames not explicitly addressed to its local hardware address, subject to hardware and network behavior. tcpdump may request this mode by default. Disable the request when it is not appropriate:
sudo tcpdump -i eth0 -p -nnPromiscuous mode does not make a host see every conversation on a switched network. A normal host generally sees its own traffic, broadcasts, multicasts, and traffic intentionally delivered to it. Other unicast traffic is usually forwarded only to its destination port. To observe traffic elsewhere, capture at the endpoint, gateway, firewall, an authorized switch mirror, or a network tap.
Forensic Collection Workflow
- Define the objective, authorized systems, interface, filter, time window, and required packet detail.
- Record the host, interface, operator, command, filter, start and end times, software version, and relevant system context.
- Check clock synchronization because accurate timestamps are important when correlating packets with logs and other evidence.
- Capture to a protected pcap file rather than relying on terminal scrollback.
- Preserve the original file, calculate an integrity hash when required, and analyze a copy.
- Restrict access because the capture may contain sensitive evidence.
- Document transformations, filters, exports, and analysis steps.
Encryption and Other Limitations
tcpdump observes packets but does not automatically decode every application protocol. TLS, SSH, VPNs, and other encryption normally prevent reading application payloads from a capture alone. Metadata may still be visible, including endpoints, ports, protocol, timing, packet sizes, connection attempts, and retransmissions.
Packet capture is one diagnostic source. Correlate it, where authorized, with application logs, endpoint telemetry, DNS records, firewall logs, load-balancer records, and flow data. An unreadable payload is not evidence that no communication occurred.
Troubleshooting Capture Problems
Permission denied or capture device cannot be opened
Confirm the intended privilege model and use sudo when authorized. Verify the interface name and availability, then review container restrictions, namespaces, mandatory access controls, and other local security policies.
No packets appear
The interface may be wrong, the BPF filter may be too restrictive, or traffic may use lo, a VPN, bridge, VLAN, or container interface. List interfaces, compare link counters, simplify the filter, and perform a controlled test. Capturing on any can help locate the traffic before narrowing the scope.
Output is slow or cluttered
Use -nn to disable host and service-name lookups, then narrow the capture with a host, network, protocol, or port expression.
The pcap grows too quickly
High traffic volume, full payload retention, and missing limits are common causes. Narrow the BPF filter, reduce snapshot length when payloads are unnecessary, rotate by size or time, cap the file count, and monitor disk capacity.
Traffic from other systems is missing
Promiscuous mode cannot overcome switching or segmentation. Capture at an approved monitoring point, endpoint, gateway, firewall, switch mirror, or tap.
Payload is unreadable
The protocol may be encrypted, binary, compressed, or truncated by the snapshot length. Use metadata for network diagnosis and correlate with authorized endpoint or application telemetry.
Packets are reported as dropped
The capture volume may exceed processing capacity, the host may be under load, or the settings may retain unnecessary payload data. Narrow the filter and time window, avoid unnecessary verbose or payload output, and consider a more suitable monitoring point.
Safe Operational Checklist
| Area | Recommended practice | Reason |
|---|---|---|
| Authorization | Obtain approval and define the permitted systems and time window. | Prevents unauthorized interception. |
| Scope | Choose one interface and a narrow BPF filter. | Reduces noise, load, and unrelated collection. |
| Sensitive payloads | Avoid -A, -X, or full payloads unless required. | Limits exposure of credentials and personal data. |
| Privileges | Use narrowly scoped sudo; do not grant broad elevated access. | Reduces privilege risk. |
| Storage | Use restrictive permissions and encrypted storage when needed. | Protects confidential traffic and evidence. |
| Retention | Delete temporary files according to approved policy. | Limits unnecessary data retention. |
| Documentation | Record command, filter, interface, operator, host, and timestamps. | Makes collection reproducible and defensible. |
| Disk capacity | Set packet, time, size, and file-count limits. | Prevents disk exhaustion. |
| Time synchronization | Check the system clock and synchronization status. | Improves correlation with other evidence. |
For related Linux administration practice, see the Linux blog and the guide to Linux administration concepts.