Search code examples
c++cpcapwinpcap

WinPcap creating empty .pcap file


Do you know how to create empty file pcap with winpcap dll? I buffer filtered packets in program memory and want to save when user click to export to .pcap file.

But when using pcap_open_offline(const char *fname, char *errbuf) can open file only if file exists. I tried fopen and other functions to create file previously (in binary mode too) but unsucessfully.

So how to get pcap_t handle pointer for pcap_dump_open(pcap_t *p, const char *fname) this way?

UPDATED: I try to use this code

fileHandle = pcap_open_offline(pcap_file_path.c_str(), errbuf);
if (errbuf == nullptr) {
    fprintf(stderr, "\nUnable to open the file %s.\n", pcap_file_path.c_str());
    return 1;
}

if (fileHandle == nullptr) {

    fprintf(stderr, "\nError to open file\n");//HERE IT FAILS
    return 1;
}

dumpfile = pcap_dump_open(fileHandle, pcap_file_path.c_str());
if (dumpfile == NULL)
{
    fprintf(stderr, "\nError opening output file\n");
    return 1;
}

SOLUTION: (Creating a pcap file)

/*create fake handle*/
fileHandle = pcap_open_dead(DLT_EN10MB, 65535);
if (fileHandle == nullptr) {
    fprintf(stderr, "\nError to open file\n");
    return 1;
}

/* Open the dump file */
dumpfile = pcap_dump_open(fileHandle, file_path.c_str());
if (dumpfile == NULL)
{
    fprintf(stderr, "\nError opening output file\n");
    return 1;
}

Solution

  • Do you know how to create empty file pcap with winpcap dll? I buffer filtered packets in program memory and want to save when user click to export to .pcap file.

    ...

    So how to get pcap_t handle pointer for pcap_dump_open(pcap_t *p, const char *fname) this way?

    pcap_dump_open() returns a pcap_dumper_t * handle for use when writing the file; a pcap_t * is used for capturing or reading, not writing.

    What you need to do, if you want to write a pcap file, is use pcap_dump_open(). If you have a pcap_t * from which you're reading or capturing the filtered packets, you should use that pcap_t * in the call to pcap_dump_open().