Circular tcpdump output

pcaptcpdump

I have external hardware that continuously sends UDP data segments over a specified port. I would like to continuously store the last few received packets in a file (could also be time-based).

If I use tcpdump with -G or -C, then either a new file is created, or the old one overwritten after the limit is reached. However, this is not what I need. I would like to have a single file that rotates continuously: as a new packet comes in, the oldest packet should be removed to make space for the new one.

This way I know I will always (after the buffer fills, of course) have a large enough sample (and not of a random size between 0 and N packets/bytes/seconds).

After some web searching, I've found that there used to be a tool called pcapture that used a circular buffer to achieve something similar, but it was short-lived and not even supported under Linux.

What would be the best approach with modern tools to achieve such circularity?

Best Answer

When you think about it, creating a circular buffer within an on-disk file is pretty complex, and not suited at all to typical disk I/O. The only way to make it even marginally feasible is to find a way to write fixed-length entries to the file, which doesn't sound like it would be a good match for a packet trace.

As suggested above, I would instead use the ringbuffer feature in tshark to create several files which the capture will use in turn. If you specify creating N files (5 to 10 would seem reasonable to me), and tell tshark to rotate after a fixed amount T of time, you will have a reasonable number of log files, an assurance that they won't accumulate over time, and easy access to something between (N-1)*T and N*T minutes of packets.

Per the tshark manual, you would need to use the -b option like so to get 6 files of 2 minutes worth of logs each (note that -b must be specified twice)

-b duration:120 -b files:6

If you need to view the whole capture in one go, you can then use the mergecap utility to merge the N logfiles into one large one to work with in Wireshark.