Sniffer4J Wiki
A java packet sniffer and forger that wraps pcap libs.
Status: Beta
Brought to you by:
bernardobl
Capture packets from a .pcap file.
This example uses a test.pcap file provided by <//http://tcpreplay.appneta.com>, but in reality you can use any .pcap file you wish.
//Create a connection to pcap
//For now let's ignore maxFrameLength, since it depends on the creation
//of filter to work.
Capture cap = new Capture(0);
try {
//Add a new adapter to the Capture Listener.
//Adapters can be of type CaptureAdapter for parsed packets, as the one in this example
//or can be the type CaptureRawAdapter to receive packets as a ByteBuffer
cap.addListener(new CaptureAdapter(){
//Count frames
private int count = 0;
//This function is called by Sniffer4J.Dll for each new received Frame
@Override
public void capture(Frame frame) {
//counting frames
count++;
//Capture length is the length actually captured by pcap
//Total length is the length of the original frame
//if maxFrameLength is used in Capture Class creation
//Those values might be different
System.out.println(" Frame Number: " + count +
" Size captured: " + frame.getCaptureLength() +
" Total Size: " + frame.getTotalLength());
}
});
//Get packets from the pcap file. The pcap file is available from:
//http://tcpreplay.appneta.com/wiki/captures.html
//https://github.com/appneta/tcpreplay
cap.connectFile("test.pcap");
//Start the Capture and block until ALL packet has been received and processed
//by CaptureAdapter
cap.CaptureFramesLoop(-1);
//Close the Capture Device
cap.close();
}catch(CaptureS4JException e){
System.err.println("Error in the connection.");
e.printStackTrace();
}catch (JNIException e) {
System.err.println("Error With the Dll");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NotSupportedDatalinkS4JException e) {
System.err.println("Datalink not Supported, only Ethernet");
e.printStackTrace();
}
The only difference from a regular capture is the connection command given by:
cap.connectFile("test.pcap");
All the rest is the same as a regular capture.