如果 pcap_next_ex() 到达 pcap 文件的末尾,则不能再次使用
pcap_next_ex() cannot be used again if it reaches the end of a pcap file
我正在分析一个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++我的数学有什么问题,为什么我的代码不能正确循环
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么我的for循环不能正确获取argv
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 为什么我不能在 FOR LOOP 中使用 i/10,C++?
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 为什么模板类中的对象不能返回值
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- ld:bind_at_load和-bitcode_bundle(Xcode设置ENABLE_bitcode=YES)不能
- 数组长度,为什么从命令行获取时不能使用它?
- Windows/Cygwin - 不能使用 pybind11 - 犯错误
- 为什么我不能使用 EGL 创建无头 OpenGl 上下文?
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 为什么我不能将一个对象push_back到属于另一个类的对象向量中?
- 为什么我不能将 rand() 与数组的大小一起使用?
- 为什么虚函数不能是静态的和全局的?
- 为什么我不能在 while 循环中创建线程?
- 如果 pcap_next_ex() 到达 pcap 文件的末尾,则不能再次使用
- Tcpdump - pcap -不能嗅探端口5984上的数据包