style="display:inline-block;width:728px;height:90px"
data-ad-client="ca-pub-7505528228218001"
data-ad-slot="1225241371">

2.1 - The Main libpcap API Overview

Java Package: org.jnetpcap


This package contains the core libpcap functions. The first thing to notice is that the programming style follows more the C convention that libpcap library was written in than Java style. That is none of the functions in the package throw any exceptions, especially the familiar java.io.IOException that is typically thrown where network communication occurs. Instead method return integer return codes, fill in error buffers with error strings, etc.

There are several reasons for this programming style. First and the most important one is that libpcap has been ported to nearly every operating system out there, literally close to a hundred. Libpcap has various small quirks that appear on different platforms. For advanced programmers these quirks are essential and is what gives libpcap its power. Instead of trying to abstract away every single possible scenario, jNP instead returns the raw data, result codes and error/warning messages. The style also makes it easy for those already familiar with the C libpcap library to just jump right in.

jNP is of course written in java and has made slight modifications to original function names such as find_all_devs has been named in java findAllDevs which is an easy adjustment for any C programmer.

The typical programming steps when working with this package is to

  1. Setup an error buffer
  2. Get a list of all available interfaces and pick one (see Pcap.findAllDevs()
  3. Open either a live network interface, discovered in previous step, or open an offline, a capture file (see Pcap.openLive() or Pcap.openOffline())
  4. Read either one packet at a time (Pcap.nextEx()) or setup a dispatch loop (see Pcap.loop() or Pcap.dispatch())
  5. If using a dispatch loop, wait in your callback method (see PcapPacketHandler.nextPacket()) and receive incoming packets.
  6. Once you have received a packet, typically the packet is either processed on the spot or put on a queue that is read by another thread
  7. When the dispatch loop exists due to either an interruption (see Pcap.breakLoop())or simply the requested number of packets at the time the loop was setup, then process the queue if it hasn't been handed off or cleanup
  8. Always the last step is to close the pcap handle (see Pcap.close()) to allow Pcap to release all its resources held

Here is a link to a fully functioning example that demonstates these basic steps:
Classic Example