Merging two pcap files with libpcap

2.4k views Asked by At

I already know how to read a pcap file and get the packets it have.B ut how can I write the packets into a new pcap file? I need this to merge two pcap files into one.

2

There are 2 answers

5
AudioBubble On BEST ANSWER

As per my comment, libpcap/WinPcap is a library, not a program, so to use libpcap/WinPcap to merge capture files, you'd have to write your own code to do the merging, using libpcap/WinPcap to read the input files and write the output files.

You could use an existing tool, such as tracemerge or Wireshark's mergecap, to merge the captures.

Assuming the goal is to merge two files' packets by time stamp, then, if you wanted to write your own code, you'd:

  • attempt to open the two files, and fail if you can't;
  • if the two files have different link-layer header types or snapshot lengths, fail (you'd have to write a pcap-ng file to handle that, and libpcap/WinPcap don't support that yet);
  • if the files have the same link-layer header types and snapshot lengths, open an output file using one of the pcap_ts (it doesn't matter which one; all the pcap_t does is tell pcap_dump_open() what link-layer header type and snapshot length to use);

and have a loop where you:

  • if there's no packet already read from the first file, and the first file is still open, read a packet from it - if that gets an EOF, close the first file;
  • if there's no packet already read from the second file, and the second file is still open, read a packet from it - if that gets an EOF, close the second file;
  • if you have two packets, write out the one with the older time stamp and mark that packet as no longer being there, so you read another packet from the file from which it came;
  • if you have only one packet, write it out and mark it as no longer being there, so you read another packet from the file from which it came;
  • if you have no packets, you're done - exit the loop;

and then, when you exit the loop, close the dump file. At that point, you're done.

2
assafmo On

This can be done using joincap.

go get -u github.com/assafmo/joincap

To merge 1.pcap and 2.pcap:

joincap 1.pcap 2.pcap > merged.pcap

I wrote joincap to overcome what I believe is bad error handling by mergecap and tcpslice.
For more details go to https://github.com/assafmo/joincap.