2.8 - Dumping captured packet to an offline file

We've covered reading packets from an offline file, what about writing captured packets to an offline file.

Libpcap library provides a mechanism for doing just that. We first open up our normal pcap capture, either online or offline, doesn't really matter, its a source of packets. Then we create a pcap dumper using PcapDumper class, that is associated with our pcap capture. Then we setup a handler and we pass into it our dumper which we instruct to dump every packet received.

StringBuilder errbuf = new StringBuilder();
String fname = "tests/test-afs.pcap";

Pcap pcap = Pcap.openOffline(fname, errbuf);

String ofile = "tmp-capture-file.cap";
PcapDumper dumper = pcap.dumpOpen(ofile); // output file

JBufferHandler<PcapDumper> dumpHandler = new JBufferHandler<PcapDumper>() {

  public void nextPacket(PcapHeader header, JBuffer buffer, PcapDumper dumper) {

    dumper.dump(header, buffer);
  }
};

pcap.loop(10, dumpHandler, dumper);
                
File file = new File(ofile);
System.out.printf("%s file has %d bytes in it!\n", ofile, file.length());
                
dumper.close(); // Won't be able to delete without explicit close
    pcap.close();

And that will do it.

If the only thing you want to do is dump packets to a file, jNetPcap provides a performance enhancing native dumper. This dumper dumps packets natively without entering "java" space.

StringBuilder errbuf = new StringBuilder();
String fname = "tests/test-afs.pcap";

Pcap pcap = Pcap.openOffline(fname, errbuf);

String ofile = "tmp-capture-file.cap";
PcapDumper dumper = pcap.dumpOpen(ofile); // output file

pcap.loop(10, dumper); // Special native dumper call to loop
                
File file = new File(ofile);
System.out.printf("%s file has %d bytes in it!\n", ofile, file.length());
                
dumper.close(); // Won't be able to delete without explicit close
    pcap.close();

The dumper is passed directly to Pcap.loop and there is no need or way to specify a user handler. A builtin native handler is provided by jNetPcap that performs the packet dump as efficiently as possible, natively.