Can anyone provide me c++ code to read a pcap file into buffer? please specify the header file that i need to add to perform the task efficiently.
I haven't tried anything because i have no idea about this.
Have you searched for the pcap library online? Asking us to find it for you is off topic, so knock yourself out.
You just need - surprise surprise - pcap.h
. Inside there's a structure for the file header, and personally I define my own 16 byte packet header structure as the pcap_pkthdr
structure in pcap.h
will be 24 bytes on 64-bit machines, but the on-disk size is always 16 bytes: it's just 32 bit ints with seconds-since-epoch, nanoseconds, length of actual data seen during capture, length of data captured in the pcap file (which can be less) - check pcap_pkthdr
for the order of the last two as I don't remember. I've only ever memory mapped the file and used the above structures to parse it. I suspect the pcap library contains functions you could use to open the file, parse the file header and packet headers if you preferred - I'm sure it'll have documentation.
If you get stuck come back with a proper question, code etc..
So, you did come back with code - pasted as comments below and formatted here for readability:
pthread_t td;
pcapNext = true;
unsigned long fileLen;
std::string pcapfile = "packet.pcap";
std::cout << "FileName :" << pcapfile << std::endl;
pcap_t* pcap;
char errbuf[PCAP_ERRBUF_SIZE];
struct pcap_pkthdr header;
pcap = pcap_open_offline(pcapfile.c_str(), errbuf);
if (pcap == NULL)
{
fprintf(stderr, "error reading pcap file: %s\n", errbuf);
exit(1);
}
int pktCount = 0;
const unsigned char* packet;
while ((packet = pcap_next(pcap, &header)) != NULL && pcapNext)
{
usleep(50000);
const unsigned char* packet1 = packet;
pktCount++;
packet = NULL;
}
fileLen = ftell(pcap);
buffer = (char*)malloc(fileLen + 1);
if (!buffer)
{
fprintf(stderr, "Memory error!");
fclose(pcap);
return;
}
fread(buffer, fileLen, 1, pcap);
std::cout << "Pcap_File_Close...." << std::endl;
fclose(pcap);
This strikes me as very weird. You'd normally want to to some processing of each packet in the while
loop, but your instead skipping over the packets then trying to read data from the end of the file: if you're at the end of the file, I assume you're reading 0 bytes but you're not checking number of bytes read or doing anything with the data. Anyway, even if you seek back to the first packet before reading the file like that, you'll scoop up all the packet headers and just have to parse it all again yourself anyway, so what's the point?