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?
The packet header and data pointers you get from libpcap/WinPcap are not valid forever.
If you're using
pcap_loop()
orpcap_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()
orpcap_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:
and
This means you may need to free those copies.