JpCap - Getting Started

Simple Packet Capture. This example is extremly simplified and based around the tutorial code that comes with JpCap. It requires the correct imports, variable definition etc to work.

1. Start Capture Engine.

m_pcap = new PacketCapture();

PacketCapture provides the core of JpCap. It is essentially a high level wrapper for libpcap.

PacketCapture implements the interface PacketCaptureCapable. This controls registration of clients to receive packet events as well as methods for setting up and tearing down packet capturing.

2. Check for devices.

m_device = m_pcap.findDevice();

findDevice() returns a String decribing the or NULL. A CaptureDeviceNotFoundException will be thrown if no network devices are prescent.

On a *nix based system device names will be in the format eth0, ppp0 etc. Windows devices will be in the format.

1 \Device\NPF_{C703C68A-51C3-4DB8-95ED-87F9AAE83059} Marvell Gigabit Ethernet Adapter (Microsoft’s Packet Scheduler)

It’s the \Device\NPF_{C703C68A-51C3-4DB8-95ED-87F9AAE83059} bit thats needed.

This example only works for a single device. For multiple devices lookupDevices() should be used, this returns a String array of all available devices.

3. Open specified device for capturing.

This requires root on a *nix system!

m_pcap.open(m_device, true);

open() requires a device, and in it’s simpliest form a boolean specifiying promiscous mode.

CaptureDeviceOpenException is thrown if the device name is invalid, or if an error occurs.

4. Add a BPF filter.

m_pcap.setFilter(FILTER, true);

setFilter() requires a filter expression (see here for more on BPF filters) and a boolean to specify optimisation. The BPF optimisation is carried out within libpcap, not JpCap.

5. Register a listener for Raw packets.

m_pcap.addRawPacketListener(new RawPacketHandler());

RawPacketHandler is an implementation of the RawPacketHandler interface.

For example:

class RawPacketHandler implements RawPacketListener {
private int counter = 0;

public void rawPacketArrived(RawPacket data) {
counter++;
}
}

This example simply adds to an incremental counter when a packet matching the filter string is received.

6. Start the capture.

m_pcap.capture(PACKET_COUNT);

capture(int count) captures the specified number of packets. If the number is infinite (-1) it will capture until stopped.

If an error occurs CapturePacketException is thrown.

See the JpCap javadoc for more information.

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.

February 28th, 2007
By Joe | filed under Network |