1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
|
package marouene;
import java.io.File;
import java.nio.ByteBuffer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.io.IOException;
import org.jnetpcap.Pcap;
import org.jnetpcap.PcapDumper;
import org.jnetpcap.PcapHandler;
import org.jnetpcap.PcapIf;
public class capture {
public static void main(String[] args) {
List<PcapIf> alldevs = new ArrayList<PcapIf>(); // Will be filled with NICs
StringBuilder errbuf = new StringBuilder(); // For any error msgs
/***************************************************************************
* First get a list of devices on this system
**************************************************************************/
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\n",
errbuf.toString());
return;
}
PcapIf device = alldevs.get(0); // We know we have atleast 1 device
/***************************************************************************
* Second we open up the selected device
**************************************************************************/
int snaplen = 1000 * 1024; // Capture all packets, no trucation
int flags = Pcap.MODE_PROMISCUOUS; // capture all packets
int timeout = 1000 * 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\n",
errbuf.toString());
return;
}
/***************************************************************************
* Third we create a PcapDumper and associate it with the pcap capture
***************************************************************************/
String ofile = "capture.cap";
PcapDumper dumper = pcap.dumpOpen(ofile); // output file
/***************************************************************************
* Fouth we create a packet handler which receives packets and tells the
* dumper to write those packets to its output file
**************************************************************************/
PcapHandler<PcapDumper> dumpHandler = new PcapHandler<PcapDumper>() {
public void nextPacket(PcapDumper dumper, long seconds, int useconds,
int caplen, int len, ByteBuffer buffer) {
dumper.dump(seconds, useconds, caplen, len, buffer);
}
};
pcap.loop(400, dumpHandler, dumper);//400 nombre de fichier à capturer
File file = new File(ofile);
System.out.printf("%s file has %d bytes in it!\n", ofile, ofile.length());
dumper.close(); // Won't be able to delete without explicit close
pcap.close();
}
} |
Partager