【问题标题】:How to filter by ip with pcap.h c++如何使用pcap.h c ++按ip过滤
【发布时间】:2017-08-25 00:31:45
【问题描述】:

我正在尝试使用 c++ 选择一组 pcap 文件的包。标准是IP。 pcap阅读器的代码:

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 文件并过滤它们的方法,也将受到欢迎。

谢谢

【问题讨论】:

    标签: c++ filter pcap


    【解决方案1】:

    来自 pcap_next_ex() 调用的数据数组将包含原始数据包字节 (pcap_next_ex man)。您需要找到包含您要过滤掉的 IPAddress 的字段的索引(很可能是 IPv4 源或目标地址字段。)

    除非您处理的是非 ipv4 情况,否则您应该有层(通用)的数据包:MAC、IPv4、协议、有效负载。 MAC 层将由 14 字节组成,这将被添加到任何索引中。 IPv4 层应该看起来像this。您看到的最后两个字段是 src 和 dst IPAddress。因此,取您需要的任何索引值,考虑 MAC 中的 14 字节,然后从该索引中提取必要的字节(IP 为 4)。使用任何网络到主机的转换,现在您就获得了一个可以与您的过滤器值进行比较的 IP。

    注意:这是过滤 ipv4 数据包的通用方法。如果您想要“通过 ip 的所有流量”,包括 ARP 或 ICMP 等协议,您将需要查看这些协议结构并找到已定义 IP 的适当字节索引。概念上与上面类似。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-01
      • 2018-03-11
      • 1970-01-01
      • 1970-01-01
      • 2014-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多