Capturing network packets using jNetPcap API

In this article, I’ll show you how to capture the network packets using Java. While studying networking you might have come across different kinds of packets, their header formats, their fields etc. But ever thought how it would be to grab one of them and study ? If yes then read on…this article will gratify your eagerness.

Here i will be using jNetPcap library. It is an open source java library, used to capture and decode network packets. It uses native implementations to provide optimum packet decoding performance.

Dependencies

Before starting, you require the following two libraries

  • WinPcap library, available here
  • jNetPcap library, available here

Setting up the environment

  1. Run and install the executable WinPcap
  2. Place the jnetpcap.jar on your project’s classpath
  3. Place the jnetpcap.dll in C:\Windows or C:\Windows\System32 directory

Capturing the packets


import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import org.jnetpcap.Pcap;
import org.jnetpcap.PcapIf;
import org.jnetpcap.packet.PcapPacket;
import org.jnetpcap.packet.PcapPacketHandler;
import org.jnetpcap.protocol.network.Arp;

public class PacketCapturer {

    public static void main(String[] args) {
        try {
            // Will be filled with NICs
            List alldevs = new ArrayList();

            // For any error msgs
            StringBuilder errbuf = new StringBuilder();

            //Getting a list of devices
            int r = Pcap.findAllDevs(alldevs, errbuf);
            System.out.println(r);
            if (r != Pcap.OK) {
                System.err.printf("Can't read list of devices, error is %s", errbuf
                        .toString());
                return;
            }

            System.out.println("Network devices found:");
            int i = 0;
            for (PcapIf device : alldevs) {
                String description =
                        (device.getDescription() != null) ? device.getDescription()
                        : "No description available";
                System.out.printf("#%d: %s [%s]\n", i++, device.getName(), description);
            }
            System.out.println("choose the one device from above list of devices");
            int ch = new Scanner(System.in).nextInt();
            PcapIf device = alldevs.get(ch);

            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

            //Open the selected device to capture packets
            Pcap pcap = Pcap.openLive(device.getName(), snaplen, flags, timeout, errbuf);

            if (pcap == null) {
                System.err.printf("Error while opening device for capture: "
                        + errbuf.toString());
                return;
            }
            System.out.println("device opened");

            //Create packet handler which will receive packets
            PcapPacketHandler jpacketHandler = new PcapPacketHandler() {
                Arp arp = new Arp();

                @Override
                public void nextPacket(PcapPacket packet, String user) {
                    //Here i am capturing the ARP packets only,you can capture any packet that you want by just changing the below if condition
                    if (packet.hasHeader(arp)) {
                        System.out.println("Hardware type" + arp.hardwareType());
                        System.out.println("Protocol type" + arp.protocolType());
                        System.out.println("Packet:" + arp.getPacket());
                        System.out.println();
                    }
                }
            };
            //we enter the loop and capture the 10 packets here.You can  capture any number of packets just by changing the first argument to pcap.loop() function below
            pcap.loop(10, jpacketHandler, "jnetpcap rocks!");
            //Close the pcap
            pcap.close();
        } catch (Exception ex) {
            System.out.println(ex);
        }
    }
}

In the above program ,statement at line 21 will capture all the network interface devices available on your system.Then you have to choose the one amongst the available interface device. Then at line 46 the openLive() is used to obtain a packet capture descriptor to look at packets on the network.

It takes five parameters

  1. device – buffer containing the name of the device
  2. snaplen – amount of data to capture per packet
  3. promisc – 1 means open in promiscious mode, 0 means non-propmiscous
  4. timeout – timeout in ms
  5. errbuf – a buffer that will contain any error messages if the call to open failed

Then at line 46, we create PacketHandler that gets notified when a new packet has been captured. And finally at line 71, we enter a loop which collects a specified number of packets and takes as argument,number of packets to capture,the user specified packet handler (jpacketHandler here in our programm) and any user defined data type (i.e a custom opaque user object ). Inside packet handler we check whether the packet contains the particular header of our interest and if it do so, display the packet.

25 thoughts on “Capturing network packets using jNetPcap API

  1. I have done all the things provided by you. But I am unable to run the program. The first error encountered in the line
    import org.jnetpcap.Pcap;
    I am running it in Netbeans.
    The intelligence window does not show the Pcap after writing
    import org.jnetpcap.
    Please suggest me the solution.

    • The error that you have mentioned signals that you have not added the jnetpcap.jar file on your classpath.
      In order to do so
      1. go to project view
      2. Right click on libraries and choose add library
      3.Then choose create library and give the name of your choice.
      4. Then customized library window will open in that under classpath tab click on Add JAR/FOLDER
      5. Then give the path of the jnetpcap.jar file. This file is present in the jnetpcap library that you have downloaded earlier, if you haven’t then download it here
      Follow this steps it will work.

      • I am using Windows 7 64 bit, Netbeans 7.3 and winpcap 4.1.3 and jnetpcap-1.3.b4-1.win64. I have followed the steps provided by you to add the library. But, still it is not working. I want to know one more thing. What project name and Main class name should I provide? I have given the project name as Example and the class name as org.jnetpcap.Example. Am I wrong? In the tutorial, the first line appears as “package org.jnetpcap.examples;” If I provide any other class name, then the program does not display the above line. So, I provided that class name. Please provide your valuable suggestion regarding this matter. I am completely in a dilemma. I have been spending lots of hours for the project, but could not proceed anyway. Please suggest me a.s.p.

  2. you mentioned that your class name is “org.jnetpcap.Example”, i.e. you have created a package named “org.jnetpcap”, which conflicts with the package name present in the jNetPcap library, because it also consists of a package with the same name. so i suggest you change your programs’ package name and let me know if it solves the problem

  3. Sorry sir, still the same problem. I think the Netbeans IDE could not find out the jnetpcap library. Should I have to paste the jnetpcap.dll inside any other directory. I have pasted it inside c:\windows\system32. .Should I have to paste the .dll inside C:\Program Files\Java\jdk1.7.0_03\bin or C:\Program Files\Java\jre7\bin?
    This time I have given the class name as Myproject. But the intelligence window does nor show jnetpcap after I write org. .Should I have to paste the .dll inside C:\Program Files\Java\jdk1.7.0_03\bin or C:\Program Files\Java\jre7\bin? Is there any other possible error in configuration? Please sir, provide your valuable suggestion..

  4. No, you don’t need to paste .dll inside bin folder. You said that you have given the class name as org.jnetpcap.MyProject. Just change it to something else say org.jnetpcapdemo.MyProject . It will work

  5. Thank you sir. I have successfully added the jnetpcap.jar and my application is now successfully capturing arp packets. I am trying to develop a packet sniffer that can capture all packets on the wire. But the code provided by you is only for arp packets. How can I filter other packets(TCP,UDP,ICMP etc.). If I change Arp to Tcp or Udp, an error message is displayed showing”cannot find symbol
    symbol: variable tcp , Create class “tcp” in package ..etc.” How shall I be able to capture tcp or udp packets? Will I have to create a class or there is some other way?

    Next I want to store the captured packets in a file. Please guide me for this. And, if possible, I wish to store and retrieve packets to and from a database.(My Sql).Shall I be? Please suggest. I will be very thankful to your help.

  6. It’s good to hear that you successfully captured the packets.
    You said that you want to capture packets other than Arp for that i suggest you to refer the jnetpcap docs. You can download it here. In the docs you will find everything you need. e.g If you want to capture all ethernet packets you directly check by adding following line of code:
    packet.hasHeader(Ethernet.ID).

  7. Hi, I’ve follow the steps you mentioned, and the problems that I encountered were there are few lines of codes with red colour underline:

    line 31 = incompatible types, required: PcapIf, found: Objects
    line 39 = incompatible types, required: PcapIf, found: Objects
    line 56 = is not abstract and does not override abstract method nextPacket(PcapPacket,Object) in PcapPacketHandler.
    line 59 = method does not override or implement a method from a supertype.

    I am using Windows 7 64-bits, Netbean 7.2, WinPCap 4.1.3, JnetpCap 1.3.0 win 64

    thanks

  8. hi, thanks for the answer, it works like a miracle. I am looking for libraries to develop a network monitoring system for college coursework, to deal with packets, those native libraries like Jnetpcap is required, do you think Jnetpcap is good enough for making a network monitoring system? I’ve also found others like Jpcap, but this one is not user friendly and it is not up to date, so I decided to use Jnetpcap. Is there any other library can use to develop network monitoring system? thanks

      • Thanks, the network monitoring system that I’m going to build also included monitoring others network devices within the network, therefore SNMP is required, do you familiar with any SNMP libraries in java? I found WebNMS provide good features of library, but I need to pay to use it. Beside, I’ve found SNMP4J is free but it seems not provide much features compare to WebNMS.

  9. am also doing my project on the same line, its quite interesting following your codes. what key characteristics of network packets play a key role in intrusion detection. an trying the code currently on packets capture.Wesley

    • Hello wesley, it would be easy for me help you if you could elaborate your project details, as far as packet capture is concerned JnetPcap is the best API to use. All the Best 🙂

  10. I have the serious problem here..i m using the netbeans..following is the output:
    Network devices found:
    #0: \Device\NPF_{DFD92806-4BF5-45D6-AFD3-F0C97F1C217D} [Microsoft]
    #1: \Device\NPF_{D50E0031-12AF-41E7-835D-CFD593544452} [Microsoft]
    #2: \Device\NPF_{8FC6436E-B957-476F-8F08-7BAF8003788A} [Realtek PCIe GBE Family Controller]
    #3: \Device\NPF_{8E71FBD8-C1D0-4286-861B-4F59688983C0} [Microsoft]
    #4: \Device\NPF_{CFF6E106-BAC3-4CB7-A48A-5B844DDD3BEE} [Microsoft]

    Choosing ‘Microsoft’ on your behalf:….

    After that..there is no any response .. can someone help me? appreciate…

    • If you are using above code then at line 38,you have to give the choice for the device to be opened amongst the listed device.In your program it is opening the device on its own without getting a choice from user. Ask user to enter a choice and one by one try each interface.

  11. compsciple do you know how I can reassemble packets using jnetpcap latest version i.e. 1.3.0. I see that they had api to reassemble packets but that api is removed from version 1.3.0.

    I have already written code which is similar to what you have done. But for 1 http call I receive 2 packets. How can I know that the 2nd packet is related to the 1st packet?

  12. Hello! i’m having issues, i’m getting this
    “Exception in thread “main” java.lang.UnsatisfiedLinkError: no jnetpcap in java.library.path
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1738)
    at java.lang.Runtime.loadLibrary0(Runtime.java:823)
    at java.lang.System.loadLibrary(System.java:1028)
    at org.jnetpcap.Pcap.(Unknown Source)
    at javaapplication8.JavaApplication8.main(JavaApplication8.java:34)
    Java Result: 1
    BUILD SUCCESSFUL (total time: 4 seconds)”
    i have done all that has been describe but still…pls any advice?

    • The issue your facing is because either you have not placed the jnetpcap.dll at right place that i have mentioned at the start of this article or there is mismatch between the version of jnetpcap and java you are using. In second case make sure that you are using the same version of java and jnetpcap i.e. either 32-bit or 64-bit. It will work

  13. Using the code provided by you, I have captured the packets in the chosen interface successfully. Now I want to display the detail data in each packet. Also, I want to save the packets in a file in .pcap format. I also want to sort the packets. I am developing a network packet analyzer. Please suggest me and provide the code for these functions.

  14. Hi,

    I am getting the following errors in red line for the above code

    in line 31 and 39, incompatible types, required: PcapIf
    in line 56, is not abstract and does not override abstract method nextPacket(org.jnetpcap.packet.PcapPacket,java.lang.Object) in org.jnetpcap.packet.PcapPacketHandler

    can u plz help me

  15. Using the code that you provided, I have captured the packets in the chosen interface successfully. Now I want to display the detail data in each packet. Also, I want to save the packets in a file in .pcap format. I also want to sort the packets. I am developing a network packet analyzer. Please suggest me and provide the code for these functions.

Leave a comment