Search code examples
linuxembedded-linuxtcpdump

How to stop writing to a capture file using tcpdump after it reaches a specific size


I am looking for some solution to stop capturing the tcpdump packet after it capture a specified size .I am using the below command to achieve this but it looks like the tcpdump is not writing all the captured packet to the specified file(myfile.pcap).

sudo tcpdump -i en0 -C 10 -W 1 -z ./stop-tcpdump.sh -w myfile.pcap -K -n

cat stop-tcpdump.sh 
#!/bin/sh
TCP_EXECUTABLE="tcpdump"
pid=$(pidof ${TCP_EXECUTABLE})
sudo kill -2 $pid

Solution

  • The easiest solution for tcpdump is probably just to increase -W 1 to -W 2. This will cause a 2nd capture file to begin to be written, but the 1st file of 10MB will remain fully intact instead of getting truncated, because the tcpdump instance won't necessarily be killed due to timing issues before that happens.

    Alternatively, you could switch to using dumpcap or tshark, both of which support an explicit -a filesize:value option, so no post-rotate kill script is needed. Note that unlike tcpdump's -C option, this option expects the value in units of kB, not MB.