Menu

Tutorial 2 Example 1

Bernardo Bulgarelli Labronici

Example 1

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.


Related

Wiki: Tutorial

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.