网络接口:您无权在该设备上捕获(套接字:不允许操作)

Network interface: you don't have permission to capture on that device (socket: Operation not permitted)

目前正在写一个查看本地带宽的小项目。我安装了这个包并实现了 pcap4j site 上可用的代码,只是为了像这样尝试一下:

import org.pcap4j.core.*;
import org.pcap4j.core.PcapNetworkInterface.PromiscuousMode;
import org.pcap4j.packet.IpV4Packet;
import org.pcap4j.packet.Packet;

import java.io.EOFException;
import java.lang.*;
import java.net.*;
import java.util.concurrent.TimeoutException;

public class BandwidthViewer {
    public static void main(String[] args) throws UnknownHostException, PcapNativeException, EOFException, TimeoutException, NotOpenException {
        InetAddress addr = InetAddress.getByName("192.168.1.8");
        PcapNetworkInterface nif = Pcaps.getDevByAddress(addr);

        int snapLen = 65536;
        PromiscuousMode mode = PromiscuousMode.PROMISCUOUS;
        int timeout = 10;
        PcapHandle handle = nif.openLive(snapLen, mode, timeout);

        Packet packet = handle.getNextPacketEx();
        handle.close();

        IpV4Packet ipV4Packet = packet.get(IpV4Packet.class);
        Inet4Address srcAddr = ipV4Packet.getHeader().getSrcAddr();
        System.out.println(srcAddr);
    }
}

一次 运行 我得到这个错误:

/usr/lib/jvm/java-11-openjdk/bin/java -javaagent:/usr/share/idea/lib/idea_rt.jar=46685:/usr/share/idea/bin -Dfile.encoding=UTF-8 -classpath /home/ivan/mdrive/Projects/IdeaProjects/BandwidthViewer/target/classes:/home/ivan/.m2/repository/org/pcap4j/pcap4j-core/2.0.0-alpha.6/pcap4j-core-2.0.0-alpha.6.jar:/home/ivan/.m2/repository/org/slf4j/slf4j-api/1.7.26/slf4j-api-1.7.26.jar:/home/ivan/.m2/repository/net/java/dev/jna/jna/5.3.1/jna-5.3.1.jar:/home/ivan/.m2/repository/org/pcap4j/pcap4j-packetfactory-static/2.0.0-alpha.6/pcap4j-packetfactory-static-2.0.0-alpha.6.jar BandwidthViewer
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Exception in thread "main" org.pcap4j.core.PcapNativeException: enp3s0: You don't have permission to capture on that device (socket: Operation not permitted)
    at org.pcap4j.core.PcapNetworkInterface.openLive(PcapNetworkInterface.java:238)
    at BandwidthViewer.main(BandwidthViewer.java:19)

Process finished with exit code 1

我可以嗅探任何数据包是有道理的,因为我 运行 以非 root 用户身份访问它。我尝试使用 this 之类的解决方案来解决此问题,但最终没有奏效。我知道这应该是可能的,因为像 Wireshark 这样的程序也需要您以 root 用户身份登录才能查看所有数据包。有人知道什么可以解决这个问题吗?显然我可以 运行 my IDE 作为 root 但这似乎没有必要。我 运行 在 Manjaro Linux 上发布这个 Linux。

我修好了。经过进一步调查,我发现我试图添加权限的文件在我的 java-8-openjdk 文件夹中,但我的项目使用 java-11-openjdk。所以我为正确的可执行文件设置了权限,它现在可以工作了。可以通过在终端中以 root 身份登录并执行以下命令来更改权限:setcap cap_net_raw,cap_net_admin=eip /path/to/java