Search code examples
c++cpacketpcap

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 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


Solution

  • 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.

    The size of memory you should allocate is in pcap_pkthdr. You have 2 length fields to consider:

    • len - contains the length of the full packet (off-wire)
    • caplen - contains the length of the data actually allocated

    Usually len and caplen will be equal but sometimes, for several possible reasons, caplen will be smaller than len