【问题标题】:pcap_next_ex() cannot be used again if it reaches the end of a pcap file如果 pcap_next_ex() 到达 pcap 文件的末尾,则不能再次使用
【发布时间】:2013-10-03 21:57:21
【问题描述】:

我正在分析一个 pcap 文件(离线模式)。首先,我需要计算文件中已经包含的数据包数量。为此,我使用“pcap_next_ex()”来循环文件,并且总是可以正常工作。我的第二个目的是挑选出每个数据包时间戳,因此我再次调用“pcap_next_ex()”,以便循环遍历 pcap 文件并填充时间戳数组(我根据 pcap 文件中包含的数据包数量动态创建)。

问题是当调用“pcap_next_ex()”时(在它达到 EOF 之后)它立即返回负值,所以我不能遍历数据包来获取时间戳并填充我的数组。

对我来说,读取 pcap 文件的指针似乎仍然停留在 EOF,需要重新初始化以指向文件的开头。我的假设是真的吗?如果答案是肯定的,如何再次指向 pcap 文件的开头?

注意:我使用的是 Visual-studio2008,windows7

这是代码:

pcap_t * pcap_ds = pcap_open_offline(pcap_file_name.c_str(), errbuf);

    struct pcap_pkthdr *header;

const u_char *data;

// Loop through pcap file to know the number of packets to analyse

int packets_number = 0;

while (int returnValue = pcap_next_ex(pcap_ds, &header, &data) >= 0)
    {
        packets_number++;
}
    // Prepare an array that holds packets time stamps
timeval* ts_array = (timeval *) malloc(sizeof(timeval) * packets_number);

     // Loop through packets and fill in TimeStamps Array 

while (int returnValue = pcap_next_ex(pcap_ds, &header, &data) >= 0)
    {

    ts_array->tv_sec = header->ts.tv_sec;
    ts_array->tv_usec = header->ts.tv_usec;
            ts_array++;
}

【问题讨论】:

    标签: c++ c winpcap


    【解决方案1】:

    您重复两次 pcap 文件只是因为您想知道其中存在多少数据包;这很容易避免。您应该使用std::vector 或其他一些动态增长的数据结构来存储时间戳:

    pcap_t * pcap_ds = pcap_open_offline(pcap_file_name.c_str(), errbuf);
    struct pcap_pkthdr *header;
    const u_char *data;
    
    std::vector<timeval> ts_array;
    // Loop through packets and fill in TimeStamps Array 
    while (int returnValue = pcap_next_ex(pcap_ds, &header, &data) >= 0) {
        timeval tv;
        tv.tv_sec = header->ts.tv_sec;
        tv.tv_usec = header->ts.tv_usec;
        ts_array.push_back(tv);
    }
    

    你去,不需要分配任何东西。

    【讨论】:

      猜你喜欢
      • 2014-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多