我正在分析一个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++;
}发布于 2013-10-03 21:57:21
您要迭代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);
}这就对了,不需要分配任何东西。
https://stackoverflow.com/questions/19161030
复制相似问题