2.6 - Reading one packet at a time

There are 2 methods provided by Pcap class for reading a single packet at a time from an open pcap capture. The first is and Pcap.nextEx().

The preferred method is to use Pcap.nextEx() according to libpcap documentation. It replaced the obsolete which had some severe limitations and quirks.

The call Pcap.nextEx() is easy to use and there are several variations of the method with exact same name:

  1. Pcap.nextEx(PcapHeader, JBuffer)
  2. Pcap.nextEx(PcapHeader, ByteBuffer)
  3. Pcap.nextEx(PcapPacket)

The first 2 methods peer (changing internal reference to point at different memory location, like set a C pointer) the capture header supplied by libpcap library itself. The second peers the buffer to the data buffer also supplied by libpcap.

The 3rd method is a little different in that, you get back a completely decoded packet and you don't have to work with raw headers and data buffers. (see Chapter 3 - Packet Decoding Framework)

Note: Notice that data is shuttled between java and native space using peering not by copying. Neither the capture header or the packet buffer is copied even once. JBuffer class provides methods that can access the native memory provided by libpcap directly just like JRE's java.nio.ByteBuffer class.

Although reading one packet at a time is easy, it is very inefficient. For bigger application it is usually necessary to setup dispatcher loops where packets are dispatched to the user much more efficiently as discussed in the next section.