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
Pcap.next() and Pcap.nextEx().
The preferred method is to use
Pcap.nextEx() according to libpcap documentation. It replaced the obsolete
Pcap.next() which had some severe limitations and quirks.
Pcap.nextEx() is easy to use and there are several variations of the method with exact same name:
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
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.