0
votes

I have a pcap file captured by wireshark, now I need to read each packet of it and write them to a vector of structure. I got some promblem with writing packets into the structure. the structure:

struct pktStruct {
    struct pcap_pkthdr * pkt_header; // header object
    const u_char * pkt_data; // data object
    long time; // used to compare with each other
};

the code how I save each packet to structure:

string resultFile = "/home/xing/Desktop/tmp.pcap";
char errbuff[PCAP_ERRBUF_SIZE]; 
pcap_t * resultPcap = pcap_open_offline(resultFile.c_str(), errbuff);
struct pcap_pkthdr * header; // header object
const u_char * data; // data object
vector<pktStruct> pktVector; // this vector contains each pktStruct
pktStruct myStruct; 
    while (int i=pcap_next_ex(resultPcap,&header,&data) >=0) {

        myStruct.pkt_header = header;
        myStruct.pkt_data = data;
        myStruct.time = header->ts.tv_sec * 1000000 + header->ts.tv_usec;
        pktVector.push_back(myStruct);
    }

when I printed each packet's information I found each structure which stored a packet is totally the same. did I save the same packet to each structure of the vector?

1

1 Answers

0
votes

The packet header and data pointers you get from libpcap/WinPcap are not valid forever.

If you're using pcap_loop() or pcap_dispatch(), after your callback returns, those packet header and data pointers passed to your callback will not point to the same data they did when your callback was running.

If you're using pcap_next() or pcap_next_ex(), after you make another call to the routine in question, the previous pointers you got from that routine will not point to the same data they did before.

So you MUST make a copy of the packet header and data:

struct pktStruct {
    struct pcap_pkthdr pkt_header; // header object - *not* a pointer
    const u_char * pkt_data; // data object
    long time; // used to compare with each other
};

and

string resultFile = "/home/xing/Desktop/tmp.pcap";
char errbuff[PCAP_ERRBUF_SIZE]; 
pcap_t * resultPcap = pcap_open_offline(resultFile.c_str(), errbuff);
struct pcap_pkthdr * header; // header object
const u_char * data; // data object
const u_char * data_copy;
vector<pktStruct> pktVector; // this vector contains each pktStruct
pktStruct myStruct; 
    while (int i=pcap_next_ex(resultPcap,&header,&data) >=0) {

        myStruct.pkt_header = *header;
        data_copy = (u_char *)malloc(myStruct.pkt_header.caplen);
        memcpy(data_copy, data, myStruct.pkt_header.caplen);
        myStruct.pkt_data = data_copy;
        myStruct.time = header->ts.tv_sec * 1000000 + header->ts.tv_usec;
        pktVector.push_back(myStruct);
    }

This means you may need to free those copies.