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!