0

I have this simple Java code that uses Jnetpcap to capture packets and print them.

public class App {
    public static void main(String[] args) throws Exception {
        ArrayList<PcapIf> alldevs = new ArrayList<PcapIf>(); // Will be filled with NICs
        StringBuilder errbuf = new StringBuilder(); // For any error msgs

        int r = Pcap.findAllDevs(alldevs, errbuf);
        
        if (r == Pcap.NOT_OK || alldevs.isEmpty()) {
            System.err.printf("Can't read list of devices, error is %s", errbuf.toString());
            
        }
        
        PcapIf device = alldevs.get(2);
        System.out.println(device.getName());// We know we have at least 1 device
        int snaplen = 64 * 1024;           // Capture all packets, no trucation
        int flags = Pcap.MODE_PROMISCUOUS; // capture all packets
        int timeout = 10 * 1000;           // 10 seconds in millis
        Pcap pcap = Pcap.openLive(device.getName(), snaplen, flags, timeout, errbuf);

        if (pcap == null) {
            System.err.printf("Error while opening device for capture: " + errbuf.toString());
            return;
        }

        PcapPacketHandler<String> jpacketHandler = new PcapPacketHandler<String>() {
            
            @Override
            public void nextPacket(PcapPacket packet, String user) {
                System.out.println(packet.toString());
                return;
        }
        };

        try {
            pcap.loop(-1, jpacketHandler, "jNetPcap");
        } finally {
            pcap.close();
        }
    }
}

as I said the code works like 1 out of 5 times when it doesn't it just keeps running and doesn't print anything. I tried in different devices and still the same weird result. can someone help me with this?

0 Answers0