2.7 - Reading multiple packets with dispatch loops

Java package: org.jnetpcap

Sophisticated applications usually need to read a lot of packets as efficiently as possible. Libpcap provides 2 dispatcher loops that buffer and dispatch packets with minimal kernel interruption.

The loops callback to user supplied functions when libpcap wants to deliver packets to the application. The exact timing of the deliveries is very libpcap implementation dependent. This is a function of the hardware architecture, network architecture nad kernel architecture.

We do not have to deal with any of that for the most part and are simply provided two functions (Pcap.loop() and Pcap.dispatch() which setup the dispatch loops. We provide a callback handler which gets called with appropriate headers, buffers and even decoded packets when libpcap is ready to deliver.

jNP does not copy packet data or headers, what it does it peers (think of setting a C pointer) java objects to native memory structures and libpcap provided data buffer. For that reason several different callback handlers are provided:

  • ByteBufferHandler class - callback signature nextPacket(PcapHeader, ByteBuffer)
  • JBufferHandler class - callback signature nextPacket(PcapHeader, JBuffer)
  • JPacketHandler class - callback signature nextPacket(JPacket)
  • PcapPacketHandler class - callback signature nextPacket(PcapPacket)

The familiar JRE class java.nio.ByteBuffer already provides what it terms direct memory access (see ByteBuffer.isDirect()). jNP library sets the physical memory that a ByteBuffer object references to that of the returned libpcap provided packet buffer. No copies are done. There is a limitation however, the memory location to which the buffer will point at can only be set at the time the ByteBuffer is being created in native JNI code, therefore although no copies of the data are made, a new ByteBuffe object is created for every callback to java world. This limitation is lifted by new JNP provided buffer described below.

jNP API adds a new type of buffer class, JBuffer, that can be manipulated more easily than a ByteBuffer class. JBuffer class provides nearly the same type of accessor methods as JRE's ByteBuffer with few exceptions. It can also be reassigned to new memory location by jNP implementation.

The last two callback handlers deal with packet objects. jNP packet framework, provides decoding capabilities to packet buffers. JPacket class is a base class for PcapPacket. Therefore if you don't neccessarily require information that is specific to pcap packets, you can work with more generic JPacket handler. However if need more advanced access to the packet and manipulation, you need to work with PcapPacket based handler. Currently only 1 type of packet is supported, that is the pcap packet. In the future new packet types and libpcap extensions may be supported.