使用 Libpcap 我正在尝试在单词级别过滤数据包。例如,如果它有单词“Hello”,我想丢弃它。
我将如何为此编写表达式???
我想我已经在 jNetPcap 论坛上回答了你,但为了确保,我也会在 SO 上发布我的答案。
基本上这里有几种方法可以完成这种过滤。由于您没有指定要如何“过滤”,因此我将描述一种在 java 中使用低级捕获过滤器和过滤器的方法。
如果您只需要查看tcp 有效负载并知道应该出现“Hello”的偏移量,我会在https://www.wireshark.org/tools/string-cf.html尝试来自 Wireshark 的捕获过滤器生成器-这允许您为 tcp 有效负载创建字符串匹配捕获过滤器。
在您的示例中(假设 tcp 有效负载偏移量为 0),捕获过滤器(采用 bpf 语法)如下所示:
not (tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x48656c6c && tcp[((tcp[12:1] & 0xf0) >> 2) + 4:1] = 0x6f)
阅读链接页面上的说明,了解到底发生了什么。注意:我添加了“不”,因为我们要丢弃与此过滤器匹配的数据包,而不是相反。
setFilter(PcapBpfProgram bpf)
您可以通过Pcap 对象在 jNetPcap 中使用此过滤器。
如果您不想将自己限制为 tcp 有效负载和固定偏移量,则不能使用捕获过滤器,需要在 java 代码中过滤此数据包。
一个例子是这个简单的 jnetpcap 数据包处理程序:
public class PacketHandler implements PcapPacketHandler<Object> {
@Override
public void nextPacket(PcapPacket packet, Object unused) {
StringBuilder str = new StringBuilder();
/*
Convert the whole packet (headers + payloads) to a string.
Adjust the first and last parameter if you don't want to look at the whole packet
*/
packet.getUTF8String(0, str, packet.getTotalSize());
String rawStringData = str.toString();
if (rawStringData.contains("Hello")) {
// we have found a packet that contains the text "Hello"
return; // ignore it
}
// do something with the packet that does not contain "Hello"
}
}
[...]
// use packet handler
pcap.loop(numberOfPackets, new PacketHandler(), null);
getUTF8Char(index)
如果您知道“Hello”的起始偏移量并且不想将整个数据包或有效负载转换为字符串,您也可以尝试该方法。