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 tcpdump

Install 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 tcpdump

Use 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 20

Do 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 show

The -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 eth0

For a controlled test, stop after 20 packets and avoid name lookups:

sudo tcpdump -i eth0 -nn -c 20

Press 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.

OptionPurposeExample useOperational note
-DList capture-capable interfacestcpdump -DUse before assuming a device name.
-iSelect an interface-i eth0Choose the interface carrying the target traffic.
-cStop after a packet count-c 20Useful for bounded tests.
-nDo not resolve host names-nAddresses remain numeric.
-nnDo not resolve host names or service names-nnReduces lookup delay and ambiguity.
-v, -vv, -vvvIncrease decoding verbosity-vvMore detail also means more clutter.
-eShow link-layer headers-eUseful for MAC addresses and VLAN-related context.
-AShow printable payload as ASCII-A 'tcp port 80'May expose credentials or sensitive content.
-XShow payload in hexadecimal and ASCII-X 'udp port 53'Useful for protocol inspection; protect the output.
-sSet snapshot length-s 128A smaller value saves space but can truncate payloads.
-wWrite a pcap-compatible binary file-w capture.pcapTerminal output is not a substitute for preserved packets.
-rRead a saved capture-r capture.pcapSupports repeatable offline analysis.
-CRotate after an approximate file size in megabytes-C 100Combine with -W to cap file count.
-GRotate after a time interval in seconds-G 300Time-based naming works with strftime patterns.
-WLimit the number of rotated files-W 12Confirm naming and overwrite behavior for your version.
-pDo not request promiscuous mode-pRestricts 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.

GoalFilter expressionWhat it selects
Traffic involving one hosthost 192.0.2.25Packets to or from that host.
Traffic from one hostsrc host 192.0.2.25Packets whose source is the host.
Traffic to one hostdst host 192.0.2.25Packets whose destination is the host.
Traffic for an IPv4 or IPv6 networknet 192.0.2.0/24Traffic involving the specified network; use a suitable IPv6 prefix when needed.
TCP traffictcpTCP packets.
UDP trafficudpUDP packets.
ICMP trafficicmpIPv4 ICMP packets, such as echo tests.
A specific portport 443Traffic using source or destination port 443.
A destination portdst port 443Traffic targeting port 443.
DNS trafficudp port 53 or tcp port 53Common UDP and TCP DNS traffic.
Combined host and port conditionhost 192.0.2.25 and tcp port 443HTTPS-related TCP traffic involving the host.
Excluding SSH administration trafficnot port 22Traffic 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 30

HTTP 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 icmp

During 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.

CharacteristicTerminal outputpcap file
Primary purposeImmediate observationCollection and later analysis
Level of retained detailMostly decoded summariesCaptured packet records up to the snapshot length
Search and repeatabilityLimited to what was displayedFilters and views can be repeated
Suitability for forensic preservationLowHigher, when properly documented and protected
Storage considerationsUses terminal or redirected text outputCan grow rapidly and requires capacity planning
Use with WiresharkNot directly useful as a packet datasetCan 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.pcap

A 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 10

At 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 -nn

Promiscuous 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

  1. Define the objective, authorized systems, interface, filter, time window, and required packet detail.
  2. Record the host, interface, operator, command, filter, start and end times, software version, and relevant system context.
  3. Check clock synchronization because accurate timestamps are important when correlating packets with logs and other evidence.
  4. Capture to a protected pcap file rather than relying on terminal scrollback.
  5. Preserve the original file, calculate an integrity hash when required, and analyze a copy.
  6. Restrict access because the capture may contain sensitive evidence.
  7. 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

AreaRecommended practiceReason
AuthorizationObtain approval and define the permitted systems and time window.Prevents unauthorized interception.
ScopeChoose one interface and a narrow BPF filter.Reduces noise, load, and unrelated collection.
Sensitive payloadsAvoid -A, -X, or full payloads unless required.Limits exposure of credentials and personal data.
PrivilegesUse narrowly scoped sudo; do not grant broad elevated access.Reduces privilege risk.
StorageUse restrictive permissions and encrypted storage when needed.Protects confidential traffic and evidence.
RetentionDelete temporary files according to approved policy.Limits unnecessary data retention.
DocumentationRecord command, filter, interface, operator, host, and timestamps.Makes collection reproducible and defensible.
Disk capacitySet packet, time, size, and file-count limits.Prevents disk exhaustion.
Time synchronizationCheck 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.