Skip to content
Advertisement

Pcap4j Library: Exception in thread “main” java.io.IOException: No NIF to capture

When I capture packets, I get the following error:

Exception in thread “main” java.io.IOException: No NIF to capture.

    at org.pcap4j.util.NifSelector.selectNetworkInterface(NifSelector.java:44)

    at io.bigdatalabs.pcaptest.App.main(App.java:22)

The code is:

  package io.bigdatalabs.pcaptest;

import java.io.IOException;
import org.pcap4j.core.BpfProgram.BpfCompileMode;
import org.pcap4j.core.NotOpenException;
import org.pcap4j.core.PacketListener;
import org.pcap4j.core.PcapHandle;
import org.pcap4j.core.PcapNativeException;
import org.pcap4j.core.PcapNetworkInterface;
import org.pcap4j.core.PcapNetworkInterface.PromiscuousMode;
import org.pcap4j.packet.Packet;
import org.pcap4j.util.NifSelector;

public class App {

    public static void main(String [] args) throws PcapNativeException, IOException, NotOpenException, InterruptedException {
        String filter = null;
        if (args.length != 0) {
            filter = args[0];
        }

        PcapNetworkInterface nif = new NifSelector().selectNetworkInterface();
        if (nif == null) {
            System.exit(1);
        }

        final PcapHandle handle = nif.openLive(65536, PromiscuousMode.PROMISCUOUS, 10);

        if (filter != null && filter.length() != 0) {
            handle.setFilter(filter, BpfCompileMode.OPTIMIZE);
        }

        PacketListener listener = new PacketListener() {
            @Override
            public void gotPacket(Packet packet) {
                printPacket(packet, handle);
            }
        };

        handle.loop(5, listener);
    }

    private static void printPacket(Packet packet, PcapHandle ph) {
        StringBuilder sb = new StringBuilder();
        sb.append("A packet captured at ")
                .append(ph.getTimestamp())
                .append(":");
        System.out.println(sb);
        System.out.println(packet);
    }

}

But I run this code with sudo command, it is running. Why don’t I run this code without sudo? I should run this code without sudo. How can I run this code?

Advertisement

Answer

In order to list and monitor your network interfaces, you need superuser privilege. That’s why you cant list any interfaces and get an Exception when you run this code without sudo.

Even famous WireShark can’t list your interfaces if you don’t run it without sudo, so i don’t think there’ll be any other solutions for you to run your application with normal privileges.

Good luck.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement