pcap_loop and pcap_dispatch Difference

Karthick picture Karthick · Feb 7, 2011 · Viewed 10k times · Source

What exactly is the difference between pcap_loop and pcap_dispatch?

Answer

mpontillo picture mpontillo · Feb 9, 2011

The manual describes this amazingly well (I'm saying that with a straight face, promise). From man pcap_loop:

   pcap_loop() processes packets from a  live  capture  or  ``savefile''
   until  cnt  packets  are  processed,  the  end of the ``savefile'' is
   reached when reading from a ``savefile'', pcap_breakloop() is called,
   or  an  error  occurs.   It  does  not return when live read timeouts
   occur.  A value of -1 or 0 for cnt is equivalent to infinity, so that
   packets are processed until another ending condition occurs.

   pcap_dispatch() processes packets from a live capture or ``savefile''
   until cnt packets are processed, the end of the current bufferful  of
   packets  is reached when doing a live capture, the end of the ``save‐
   file'' is reached when reading from a ``savefile'',  pcap_breakloop()
   is  called, or an error occurs.  Thus, when doing a live capture, cnt
   is the maximum number of packets to process before returning, but  is
   not a minimum number; when reading a live capture, only one bufferful
   of packets is read at a time, so fewer than cnt packets may  be  pro‐
   cessed. A value of -1 or 0 for cnt causes all the packets received in
   one buffer to be processed when reading a live  capture,  and  causes
   all  the  packets  in the file to be processed when reading a ``save‐
   file''.

I know you didn't really want to read and understand all that, so let's break it down.

Both functions:

  • Process packets from a live capture or "savefile" until any of these conditions occur:
    • the specified count is reached
    • the end of the "savefile" is reached
    • pcap_breakloop() is called
    • an error occurs
  • Consider -1 or 0 to essentially mean "process an infinite number of packets" - that is, until another end condition occurs. (-1 is recommended for interoperability with older versions, later in the manual)

pcap_dispatch() alone

  • Also returns after the end of the current bufferful of packets is reached, when doing a live capture (in other words, can return more often, since the specified count is not a minimum)