首页 > 解决方案 > pcap4j+winpcap 我应该手动运行 rpcapd.exe 吗?

问题描述

嗨,我已经手动下载了 pcap4j 和 winpcap 以及所有 jar(jna、pcap4j-core-1.8.2、slf4j-api-1.7.25、slf4j-simple-1.7.25)依赖项。添加到项目中并编译良好。但是:当我开始嗅探 packet.getHeader() 并且 packet.getPayload() 返回 null 时!如果我手动运行 rpcapd.exe 那么它可以工作......为什么?

package sniffer;

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 {

    static PcapNetworkInterface getNetworkDevice() {
        PcapNetworkInterface device = null;
        try {
            device = new NifSelector().selectNetworkInterface();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return device;
    }

    public static void main(String[] args) throws PcapNativeException, NotOpenException {
        // The code we had before
        PcapNetworkInterface device = getNetworkDevice();
        System.out.println("You chose: " + device);

        // New code below here
        if (device == null) {
            System.out.println("No device chosen.");
            System.exit(1);
        }

        // Open the device and get a handle
        int snapshotLength = 65536; // in bytes   
        int readTimeout = 50; // in milliseconds                   
        final PcapHandle handle;
        handle = device.openLive(snapshotLength, PromiscuousMode.PROMISCUOUS, readTimeout);
        String filter = "tcp port 80";
        handle.setFilter(filter, BpfCompileMode.OPTIMIZE);

        // Create a listener that defines what to do with the received packets
        PacketListener listener = new PacketListener() {
            @Override
            public void gotPacket(Packet packet) {
                // Override the default gotPacket() function and process packet
                System.out.println(handle.getTimestamp());
                System.out.println(packet);
System.out.println(packet.getHeader());///////////////<<<<<<<<<<<------------
            }
        };

        // Tell the handle to loop using the listener we created
        try {
            int maxPackets = 50;
            handle.loop(maxPackets, listener);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // Cleanup when complete
        handle.close();
    }

}

标签: winpcappcap4j

解决方案


您需要在类路径中添加一个数据包工厂(例如 pcap4j-packetfactory-static.jar),或者 Pcap4J 为所有数据包创建 UnknownPacket 实例,getPayload() 和 getHeader() 返回 null。


推荐阅读