Time-based Packet Capture with tcpdump
Time-based Packet Capture with tcpdump
Efficiently capture network traffic for a specific time interval using tcpdump's built-in file rotation. This method is ideal for monitoring network interfaces without needing external scripts or cron jobs, as it automatically resets the capture file after a set duration.
Choosing Your Capture Method
Before running the command, decide what traffic you need to see. This will determine which command and interface you use.
- Specific Container/VM Interface: Use this when you want to see all traffic entering or leaving a specific virtual machine or Docker container. You must first identify its virtual interface (`veth`) on the host.
- Specific Host and Port: Use this when you want to see all traffic to or from a specific service (e.g., a web server or database) regardless of which interface it uses. This is often the most practical method for troubleshooting application-level issues.
Capture Commands
Here are two primary methods for time-rotated captures. All examples save to a single file that is overwritten every 10 minutes.
Method 1: Capture by Specific Interface
This command is ideal for monitoring all traffic on a known interface, like a container's `veth` adapter.
sudo tcpdump -i vethec9ed9c -w /tmp/capture.pcap -G 600 -W 1
Method 2: Capture by Host and Port
This command captures traffic related to a specific host and port, which is useful for monitoring a backend service.
sudo tcpdump -i any -w /tmp/capture.pcap -G 600 -W 1 'host hostname.asd.local and port 12345'
Parameter Breakdown
-i <interface>: Specifies the network interface to monitor (e.g.,vethec9ed9c,eth0, orany).-w /tmp/capture.pcap: Writes the raw packet output to a file. This is required to use the rotation feature.-G 600: Sets the rotation interval in seconds. It triggers a file rotation every 600 seconds (10 minutes).-W 1: Limits the number of capture files to one. When the interval from-Gelapses, tcpdump overwrites this single file.'host ... and port ...': A filter expression to capture only the traffic that matches the specified criteria. Always enclose filters in single quotes to prevent shell interpretation.
Running as a Background Process
To run a capture continuously, it's best to run it as a background process using `nohup` and `&`. This ensures the capture continues even if your terminal session closes.
nohup sudo tcpdump -i any -w /tmp/capture.pcap -G 600 -W 1 'host hostname.asd.local and port 12345' &
To stop the capture, find its process ID and use the `kill` command:
# Find the Process ID (PID) of tcpdump
pgrep tcpdump
# Stop the process using its PID
sudo kill <PID>