Issue capturing packets from pcap file using JNetPcap

267 Views Asked by At

I'm using JNetPcap to capture packets from a pcap file in Java. The code works fine sometimes, but other times it doesn't capture any packets even though the pcap file is full of packets.

Here's my code:

import org.jnetpcap.Pcap;
import org.jnetpcap.packet.PcapPacketHandler;

public class OfflinePcapCapture {
    public static void main(String[] args) {
        String pcapFilePath = "D:/hello/1212.pcap";
        StringBuilder errorBuffer = new StringBuilder();
        Pcap pcap = Pcap.openOffline(pcapFilePath, errorBuffer);
        if (pcap == null) {
            System.err.println("Error opening pcap file: " + errorBuffer);
            return;
        }

        PcapPacketHandler<String> packetHandler = (packet, user) -> System.out.println(packet.toString());

        int packetCount = pcap.loop(-1, packetHandler, "");
        if (packetCount < 0) {
            System.err.println("Error capturing packets: " + pcap.getErr());
        } else {
            System.out.println("Captured " + packetCount + " packets from " + pcapFilePath);
        }
        pcap.close();
    }
}

I've tried removing the filter expression to capture all packets in the file, but that didn't change anything. Sometimes the code captures packets from the file, and other times it doesn't capture any packets even though the file is full of packets.

One thing I noticed is that sometimes the code captures packets from the file on the first try, and other times I have to rerun the code multiple times to get a result.

Any help on resolving this issue would be greatly appreciated. Thank you in advance!

1

There are 1 best solutions below

0
schneida On

I had the same issues with jnetpcap loop not working reliably any more (in my case with Java 11, Java 8 worked fine). The solution was to switch to using the nextEx API like so:

StringBuilder errorBuffer = new StringBuilder();
final Pcap pcap = Pcap.openOffline("C:\\dumpcap.pcap", errorBuffer);
final PcapPacket packet = new PcapPacket(JMemory.Type.POINTER);

int packetCount = 0;
while (!Thread.currentThread().isInterrupted()) {
    int resultCode = pcap.nextEx(packet);
    if (resultCode == 1) {
        System.out.println("Recorded packet " + packet);
        packetCount++;
    } else if (resultCode != 0) {
        System.out.println("Finished reading: " + resultCode);
        //0 means that there was not packet, but that's generally OK - aynthing else and we should abort
        break;
    }
}
System.out.println("Read packets: " + packetCount);

pcap.close();