- Tutorials
- API Examples
- User Guide
- Ch 1 - The Basics
- Ch 2 - libpcap
- 2.1 - The Main libpcap API Overview
- 2.2 - Getting a List of Interfaces
- 2.3 - Opening a Network Interface for Capture
- 2.4 - Opening offline capture
- 2.5 - Setting a packet filter
- 2.6 - Reading one packet at a time
- 2.7 - Reading multiple packets with dispatch loops
- 2.8 - Dumping captured packet to an offline file
- 2.9 - Transmitting packets
- 2.10 - Close Pcap and PcapDumper handles
- Ch 3 - Packet Decoding
- Ch 4 - Internals
- Ch 5 - Protocols
- Ch 6 - Native API
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.
»
Printer-friendly- Login or register to post comments
Send via Email
PDF Convert