Module org.jnetpcap

Package org.jnetpcap


package org.jnetpcap
The Packet Capture library provides a high level interface to packet capture systems. All packets on the network, even those destined for other hosts, are accessible through this mechanism. It also supports saving captured packets to a savefile, and reading packets from a savefile.

Opening a capture handle for reading

To open a handle for a live capture, given the name of the network or other interface on which the capture should be done, call Pcap.create(String), set the appropriate options on the handle, and then activate it with Pcap.activate(). If activate() fails, the handle should be closed with Pcap.close().

To obtain a list of devices that can be opened for a live capture, call Pcap.findAllDevs(); the returned list contains PcapIf objects representing each interface. Pcap.lookupDev() will return the first device on that list that is not a loopback network interface.

To open a handle for a savefile from which to read packets, given the pathname of the savefile, call Pcap.openOffline(String). To set up a handle for writing to a savefile, use Pcap.dumpOpen(String).

To create a "fake" handle for use in routines that require a Pcap instance as an argument, such as routines to compile a filter expression, call Pcap.openDead(PcapDlt, int).

All Pcap instances implement AutoCloseable, so they can be used with try-with-resources statements to ensure proper cleanup. When you're done with a handle, it will be automatically closed when exiting the try block.

Example Usage

Here is an example which demonstrates capturing packets using different handler types:

 try (Pcap pcap = Pcap.openOffline("capture.pcap")) {
 	// Create and apply a filter
 	BpFilter filter = pcap.compile("tcp", true);
 	pcap.setFilter(filter);
 
 	// Capture packets using byte array handler
 	pcap.loop(1, (String msg, PcapHeader header, byte[] packet) -> {
 		System.out.printf("Packet [timestamp=%s, wirelen=%d caplen=%d]%n",
 				Instant.ofEpochMilli(header.toEpochMillis()),
 				header.wireLength(),
 				header.captureLength());
 	}, "Example message");
 
 	// Capture packets using ByteBuffer handler for zero-copy
 	pcap.loop(1, (String msg, PcapHeader header, ByteBuffer packet) -> {
 		System.out.printf("Packet [timestamp=%s, wirelen=%d caplen=%d]%n",
 				Instant.ofEpochMilli(header.toEpochMillis()),
 				header.wireLength(),
 				header.captureLength());
 	}, "Example message");
 }
 

Packet Handlers

The library provides several types of packet handlers through the PcapHandler interface:

Network Interfaces

Network interfaces are represented by the PcapIf class, which provides information about:
  • Interface name and description
  • Network addresses (IPv4, IPv6)
  • Interface flags and capabilities
  • Hardware (MAC) addresses
Author:
Mark Bednarczyk [mark@slytechs.com], Sly Technologies Inc.