Jnetpcap公式インスタンス(4)-取得したパケットをファイルに書き込む
5350 ワード
PcapDumerクラスでは、pcapがキャプチャしたpacketをpcap形式の保存ファイルに「ダンプ」することができます.
package org.jnetpcap.examples;
import java.io.File;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import org.jnetpcap.Pcap;
import org.jnetpcap.PcapDumper;
import org.jnetpcap.PcapHandler;
import org.jnetpcap.PcapIf;
public class PcapDumperExample {
public static void main(String[] args) {
List alldevs = new ArrayList();
StringBuilder errbuf = new StringBuilder();
/***************************************************************************
*
**************************************************************************/
int r = Pcap.findAllDevs(alldevs, errbuf);
if (r == Pcap.NOT_OK || alldevs.isEmpty()) {
System.err.printf("Can't read list of devices, error is %s
",
errbuf.toString());
return;
}
PcapIf device = alldevs.get(1); // We know we have atleast 1 device
/***************************************************************************
*
**************************************************************************/
int snaplen = 64 * 1024; // Capture all packets, no trucation
int flags = Pcap.MODE_PROMISCUOUS; // capture all packets
int timeout = 10 * 1000; // 10 seconds in millis
Pcap pcap = Pcap.openLive(device.getName(), snaplen, flags, timeout, errbuf);
if (pcap == null) {
System.err.printf("Error while opening device for capture: %s
",
errbuf.toString());
return;
}
/***************************************************************************
* pcap pcapdumper
***************************************************************************/
String ofile = "tmp-capture-file.cap";
PcapDumper dumper = pcap.dumpOpen(ofile); // output file
/***************************************************************************
* handler dumper
**************************************************************************/
PcapHandler dumpHandler = new PcapHandler() {
public void nextPacket(PcapDumper dumper, long seconds, int useconds,
int caplen, int len, ByteBuffer buffer) {
dumper.dump(seconds, useconds, caplen, len, buffer);
}
};
/***************************************************************************
* loop 10 , dumper
**************************************************************************/
pcap.loop(10, dumpHandler, dumper);
File file = new File(ofile);
System.out.printf("%s file has %d bytes in it!
", ofile, file.length());
/***************************************************************************
* dumper handler
**************************************************************************/
dumper.close(); // dumper ,
pcap.close();
if (file.exists()) {
file.delete();
// , , wireshark
}
}
}