如果 pcap_next_ex() 到达 pcap 文件的末尾,则不能再次使用

pcap_next_ex() cannot be used again if it reaches the end of a pcap file

本文关键字:pcap 不能 ex next 到达 如果 文件      更新时间:2023-10-16

我正在分析一个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++;
}
你迭代

两倍的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);
}

好了,无需分配任何东西。