tcpdump – dump raw packets to file while also following on screen

The following will create a dump of raw network packets to a file, while continuously reading that file and displaying the packets on screen in human-readable format:

/bin/sh -c "tcpdump -i any -w /tmp/dumpfile.cap host 127.0.0.1 &" && sleep 1; \
    tail -n 1000 -f /tmp/dumpfile.cap | tcpdump -r -

Explanation:

  • /bin/sh -c "tcpdump -i any -w /tmp/dumpfile.cap host 127.0.0.1 &" : run tcpdump in the background, dumping raw packets to /tmp/dumpfile.cap
  • sleep 1 : wait a second for the file to be created and the header to be written to it. without waiting, you’ll probably get “bad dump file format”
  • tail -n 1000 -f /tmp/dumpfile.cap : tail the dump file. The point of -n is to get the whole file, from the start, including the header. Avoids “bad dump file format” error
  • tcpdump -r - : reads from stdin, which is actually the contents of /tmp/dumpfile.cap and displays to stdout in human-readable format.

IMPORTANT: Interrupting with CTRL+C will NOT kill the backgrounded tcpdump. Don’t forget to do that too if it’s not limited somehow, otherwise it will fill up the disk.