gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:54:27 26 4
gpt4 key购买 nike

我正在分析一个 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);
}

好了,不需要分配任何东西。

关于c++ - pcap_next_ex() 如果到达 pcap 文件的末尾则不能再次使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19161030/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com