简体   繁体   English

C ++-如何在向量中使用pcap_next_ex存储脱机读取数据包?

[英]C++ - How can I store offline read packets using pcap_next_ex in vector?

I read packets stored in files using 我使用以下命令读取了存储在文件中的数据包

struct pcap_pkthdr *header;
const u_char *packetData;
pcap_next_ex(pcap, &header, &packetData)

and I need to read all packets and store every packet (packet header and packet data) in vector of struct 我需要读取所有数据包并将每个数据包(数据包头和数据包数据)存储在struct的向量中

struct packetStruct {
    struct pcap_pkthdr *header;
    const u_char *packetData;
};

But when I only assign pointers pointng to memory with header and packet data to this struct pointers and push this struct to vector, all pointers in vector points to the last packet after reading loop (function stores packets in same memory). 但是,当我只将指向带有内存头和数据包数据的指向内存的指针指向此结构指针并将该结构推入向量时,向量中的所有指针都指向读取循环后的最后一个数据包(函数将数据包存储在同一内存中)。

Should I allocate new memory for header and packet data and if so, how big this memory should be? 我应该为头和包数据分配新的内存吗?如果是,此内存应该有多大? Or is there another way? 还是有另一种方法?

Thanks for replies 感谢您的答复

Yes, you should allocate new memory for the header and packet. 是的,您应该为标头和数据包分配新的内存。 The pointers you get from pcap_next_ex are re-used by libpcap/WinPcap so you cannot assume the memory allocated for a certain packet will be available when the next packet arrives, and so on. pcap_next_ex获取的指针将由libpcap / WinPcap重新使用,因此您不能假设为下一个数据包到达而分配给特定数据包的内存将可用,依此类推。

The size of memory you should allocate is in pcap_pkthdr . 您应该分配的内存大小在pcap_pkthdr You have 2 length fields to consider: 您有2个长度字段需要考虑:

  • len - contains the length of the full packet (off-wire) len包含完整数据包的长度(离线)
  • caplen - contains the length of the data actually allocated caplen包含实际分配的数据的长度

Usually len and caplen will be equal but sometimes, for several possible reasons, caplen will be smaller than len 通常lencaplen相等,但有时由于多种可能的原因, caplen小于len

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM