Guides

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 receive.

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.