winpcap - 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();
}
}
解决方案
您需要在类路径中添加一个数据包工厂(例如 pcap4j-packetfactory-static.jar),或者 Pcap4J 为所有数据包创建 UnknownPacket 实例,getPayload() 和 getHeader() 返回 null。
推荐阅读
- django - Django models.py(API 结果) - 检索当前帖子以添加 api 结果
- c# - 如何在 C# windows 应用程序中添加打印机路径?
- r - 在 R 中循环一个函数
- reactjs - 在 React 中管理多个输入时
- java - 在我的 postgres 模式中的任何表中执行任何插入/更新/删除操作后,是否可以调用我的 java 函数
- c - c lang,switch case中的双打印语句
- r - 绘制多个时间序列对象的平均值并说明该图中的误差
- javascript - 使用 jQuery 或 Javascript 从 HTML 表单输入构造一个 url
- javascript - 查找并替换文本文件中的所有 javascript 变量
- appium - 运行 Appium-doctor 时出现错误