What I actually want to do is measure tcpdump for 10s.

$ timeout 10s tcpdump > my.log

but I found there has only a short period actually being logged, instead of whole 10s.

therefore I did this experiment:

# a.sh
tcpdump & p1=$!

sleep 10s;                  
echo "Checkpoint #1"        
kill $p1;              
$ sudo ./a.sh # works as expected
$ sudo ./a.sh > my.log # not as expected
# it printed

so it actually only logged 2s.

Q1: How to do what I want?

Q2: Why print into the terminal(or pts?) is faster than into files. (I guess it's the reason.)

  • 1
    tcpdump (formatted) output to a file may be buffered, and when timeout kills it, or your script does, anything still in the buffer is lost. Try -l (lower ell) or -U and maybe --immediate-mode also. – dave_thompson_085 Apr 19 '20 at 2:14
  • @dave_thompson_085 got it, thanks a lot! – Ftyn Apr 22 '20 at 2:50

When its standard output is a tty, tcpdump turns on "immediate mode" (via pcap_set_immediate_mode(3), on systems which support it) and (since tcpdump is using stdio functions for output) the output will be line buffered by default.

But when redirecting tcpdump's output to a file or pipe, you'll have to force both immediate mode and line buffering explicitly if you want the packets to be logged "live" into the file.

tcpdump --immediate-mode -l > my.log

You may also want to use the -n option, without which tcpdump would try to reverse lookup the addresses via DNS, which may take a lot of time.

tcpdump --immediate-mode -nl > my.log

When not using tcpdump interactively, it's much better to dump the raw packets with -w and parse them when reading the dump file with -r. In that case, -U should be used instead of -l if you want the dump output to be "live".

tcpdump --immediate-mode -Uw /path/to/dump
tail -c+0 -f /path/to/dump | tcpdump -r-
  • Thank you for your response, it's so detailed, really helped. – Ftyn Apr 22 '20 at 2:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.