如何使用 pcap.h c++ 按 ip 过滤
How to filter by ip with pcap.h c++
我正在尝试 select 一组带有 c++ 的 pcap 文件的包。标准是IP。
pcap的代码reader:
readPcap()
{
//Filter packages with ip = 192.168.15.40
std::vector<std::string> rmc;
std::string path = "../../imu10000.pcap";
char errbuff[PCAP_ERRBUF_SIZE];
pcap_t *pcap = pcap_open_offline(path.c_str(), errbuff);
struct pcap_pkthdr *header;
const unsigned char *data;
while (int returnValue = pcap_next_ex(pcap, &header, &data) >= 0)
{
if (header->len != header->caplen)
printf("Warning! Capture size different than packet size: %d bytes\n", header->len);
// We also have a function that does this similarly below: PrintData()
for (u_int i=0; (i < header->caplen ) ; i++)
{
// Start printing on the next after every 16 octets
if ( (i % 16) == 0) printf("\n");
// Print each octet as hex (x), make sure there is always two characters (.2).
printf("%.2x ", data[i]);
}
}
}
目前,代码正在以十六进制打印所有包的主体,但文件中有 10,000 个包,其中一半来自其他 IP。
您知道如何按 IP 过滤以便我可以只读取我需要的包吗?
如果您知道另一种读取pcap文件并过滤它们的方法,也将受到欢迎。
谢谢
来自 pcap_next_ex() 调用的数据数组将包含原始数据包字节 (pcap_next_ex man)。您需要找到包含您要过滤掉的 IP 地址的字段的索引(很可能是 IPv4 源或目标地址字段。)
除非您处理的是非 ipv4 情况,否则您应该拥有层为(一般化)的数据包:MAC、IPv4、协议、有效负载。 MAC 层将包含 14 个字节,这将被添加到任何索引。而 IPv4 层应该看起来像 this。您看到的最后两个字段是 src 和 dst IP 地址。因此,采用您需要的任何索引值,考虑 MAC 中的 14 个字节,然后从该索引中提取必要的字节(IP 为 4 个字节)。使用任何网络到主机的转换,现在您获得了一个可以与您的过滤值进行比较的 IP。
注意:这是过滤 ipv4 数据包的通用方法。如果您想要 "all traffic via an ip",包括 ARP 或 ICMP 等协议,您将需要查看这些协议结构并找到已定义 IP 的适当字节索引。它在概念上与上述类似。
我正在尝试 select 一组带有 c++ 的 pcap 文件的包。标准是IP。 pcap的代码reader:
readPcap()
{
//Filter packages with ip = 192.168.15.40
std::vector<std::string> rmc;
std::string path = "../../imu10000.pcap";
char errbuff[PCAP_ERRBUF_SIZE];
pcap_t *pcap = pcap_open_offline(path.c_str(), errbuff);
struct pcap_pkthdr *header;
const unsigned char *data;
while (int returnValue = pcap_next_ex(pcap, &header, &data) >= 0)
{
if (header->len != header->caplen)
printf("Warning! Capture size different than packet size: %d bytes\n", header->len);
// We also have a function that does this similarly below: PrintData()
for (u_int i=0; (i < header->caplen ) ; i++)
{
// Start printing on the next after every 16 octets
if ( (i % 16) == 0) printf("\n");
// Print each octet as hex (x), make sure there is always two characters (.2).
printf("%.2x ", data[i]);
}
}
}
目前,代码正在以十六进制打印所有包的主体,但文件中有 10,000 个包,其中一半来自其他 IP。
您知道如何按 IP 过滤以便我可以只读取我需要的包吗?
如果您知道另一种读取pcap文件并过滤它们的方法,也将受到欢迎。
谢谢
来自 pcap_next_ex() 调用的数据数组将包含原始数据包字节 (pcap_next_ex man)。您需要找到包含您要过滤掉的 IP 地址的字段的索引(很可能是 IPv4 源或目标地址字段。)
除非您处理的是非 ipv4 情况,否则您应该拥有层为(一般化)的数据包:MAC、IPv4、协议、有效负载。 MAC 层将包含 14 个字节,这将被添加到任何索引。而 IPv4 层应该看起来像 this。您看到的最后两个字段是 src 和 dst IP 地址。因此,采用您需要的任何索引值,考虑 MAC 中的 14 个字节,然后从该索引中提取必要的字节(IP 为 4 个字节)。使用任何网络到主机的转换,现在您获得了一个可以与您的过滤值进行比较的 IP。
注意:这是过滤 ipv4 数据包的通用方法。如果您想要 "all traffic via an ip",包括 ARP 或 ICMP 等协议,您将需要查看这些协议结构并找到已定义 IP 的适当字节索引。它在概念上与上述类似。