当我捕获数据包时,出现以下错误:
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)
代码是:
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);
}
}
但是我用 sudo 命令运行这段代码,它正在运行。为什么我不使用 sudo 运行这段代码?我应该在没有 sudo 的情况下运行这段代码。如何运行此代码?
最佳答案
为了列出和监控您的网络接口(interface),您需要 super 用户权限。这就是为什么在没有 sudo 的情况下运行此代码时无法列出任何接口(interface)并获得异常的原因。
如果您在没有 sudo 的情况下不运行它,即使是著名的 WireShark 也无法列出您的接口(interface),因此我认为没有任何其他解决方案可以让您以正常权限运行您的应用程序。
祝你好运。
关于java - Pcap4j 库 : Exception in thread "main" java. io.IOException:没有要捕获的 NIF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49318787/