This example demonstrates how to capture network packages with pcap and Java.
To run the examples you will need to install libpcap for your operation system. For Windows download and install WinPcap.
Ubuntu users can install libpcap running this command:
sudo apt-get install libpcap-dev
We will use jNetPcap as Java wrapper. The following examples require version 1.4
List Network Devices
import java.util.ArrayList; import java.util.List; import org.jnetpcap.Pcap; import org.jnetpcap.PcapIf; public class NetworkInterfaces { 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 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; } 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); } } }
Capture Packages
Following complete example captures first 10 packages:
import java.util.ArrayList; import java.util.List; import org.jnetpcap.Pcap; import org.jnetpcap.PcapIf; import org.jnetpcap.packet.PcapPacket; import org.jnetpcap.packet.PcapPacketHandler; import org.jnetpcap.protocol.network.Ip4; public class PackageCapture { 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 int r = Pcap.findAllDevs(alldevs, errbuf); if (r != Pcap.OK || alldevs.isEmpty()) { 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); } PcapIf device = alldevs.get(0); // Get first device in list System.out.printf("\nChoosing '%s' on your behalf:\n", (device.getDescription() != null) ? device.getDescription() : device.getName()); 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: " + errbuf.toString()); return; } PcapPacketHandler<String> jpacketHandler = new PcapPacketHandler<String>() { public void nextPacket(PcapPacket packet, String user) { byte[] data = packet.getByteArray(0, packet.size()); // the package data byte[] sIP = new byte[4]; byte[] dIP = new byte[4]; Ip4 ip = new Ip4(); if (packet.hasHeader(ip) == false) { return; // Not IP packet } ip.source(sIP); ip.destination(dIP); /* Use jNetPcap format utilities */ String sourceIP = org.jnetpcap.packet.format.FormatUtils.ip(sIP); String destinationIP = org.jnetpcap.packet.format.FormatUtils.ip(dIP); System.out.println("srcIP=" + sourceIP + " dstIP=" + destinationIP + " caplen=" + packet.getCaptureHeader().caplen()); } }; // capture first 10 packages pcap.loop(10, jpacketHandler, "jNetPcap"); pcap.close(); } }
if you want to capture specific packages you can set a filter like this:
PcapBpfProgram filter = new PcapBpfProgram(); String expression = "tcp port 3724 or tcp port 1119"; int optimize = 0; // 0 = false int netmask = 0xFFFFFF00; // 255.255.255.0 if (pcap.compile(filter, expression, optimize, netmask) != Pcap.OK) { System.err.println(pcap.getErr()); return; } if (pcap.setFilter(filter) != Pcap.OK) { System.err.println(pcap.getErr()); return; }
I am getting this error.Can you help me?
Choosing ‘Microsoft’ on your behalf:
Mar 16, 2016 11:03:10 AM java.util.logging.LogManager$RootLogger log
SEVERE: JLogger.static: Unable to find builtin-logger.properties. Is resources
directory missing in JAR File?
Mar 16, 2016 11:03:10 AM org.jnetpcap.util.config.JConfig
SEVERE: JConfig.static: unable to find builtin-config.properites. Is resources
directory in JAR file?
Mar 16, 2016 11:03:10 AM org.jnetpcap.util.config.JConfig
SEVERE: JConfig.static3: unable to find builtin-logger.properties. Is resource
s directory in JAR file?
Did you added jnetpcp.jar to your project? Also you need to bind the folder containing the native dll files in “Native library location” for jnetpcap.jar. DLLs and jnetpcap.jar are found in downloadable zip file, mentioned in the beginning of the tutorial
hello i have problem to run it
Exception in thread “main” java.lang.UnsatisfiedLinkError: no jnetpcap in java.library.path
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1886)
at java.lang.Runtime.loadLibrary0(Runtime.java:849)
at java.lang.System.loadLibrary(System.java:1088)
at org.jnetpcap.Pcap.(Unknown Source)
at javaapplication5.NetworkInterfaces.main(NetworkInterfaces.java:17)
C:\Users\KASYFI\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
please help i really need to make it run perfectly
Hello Kasper292,
Please check if you have jnetpcap.dll in your java.library.path
Also make sure you have winpcap installed, that will also cause this type of error even though jnetpcap.dll is found, but one of its dependencies is not.
“Can’t read list of devices, error is %s” on screen
I have a project related to network listening (packet capture) in Java. I did not understand exactly what this code did.
you will see the error “Can’t read list of devices, error is %s” either if 1) Pcap can’t find your network devices or 2) there was an error while trying to do 1) In both cases I will suggest following: 1) debug your application an look if alldevs List is filled with data 2) try to run your program on another device and compare the results 3) If non of those helps, rise a question in StackOverflow, describing what you have done, your hardware configuration (network cards) and share the link here, so we can try to help (comments are… Read more »
Can’t make it work, not packet capture, I’m having the result of:
Network devices found:
#0: \Device\NPF_{D7316869-2F96-43B6-A764-1DF411583932} [Realtek PCIe GBE Family Controller]
#1: \Device\NPF_{66FE4DFF-D8E5-4F26-B1CC-B7686E226CC1} []
Choosing ‘Realtek PCIe GBE Family Controller’ on your behalf:
I called the class :
PackageCapture.main(new String[0]);
Hi Seynal,
I suggest you debug the app and watch for the content of the PcapPacket packet object. Note in the example above that non IP packages will be filtered out
if (packet.hasHeader(ip) == false) { return; }
Maybe in your case the first 10 packages are non IP packages – please check while debugging
Can i get data in readable from i.e. PcapPacket to HEX or string
when i select microsoft as a network device than its give me a packet but the source id and destination ip both 0.0.0.0 why?plz help me
Hi Utsav,
It will be hard to solve your problem here in the comments. I suggest you open a question in StackOverflow with complete description and source code and than post the link here.
Thanks!
I getting. this error. Can you help me?
Exception in thread “main” java.lang.UnsatisfiedLinkError: com.slytechs.library.NativeLibrary.dlopen(Ljava/lang/String;)J
at com.slytechs.library.NativeLibrary.dlopen(Native Method)
at com.slytechs.library.NativeLibrary.(Unknown Source)
at com.slytechs.library.JNILibrary.(Unknown Source)
at com.slytechs.library.JNILibrary.loadLibrary(Unknown Source)
at com.slytechs.library.JNILibrary.register(Unknown Source)
at com.slytechs.library.JNILibrary.register(Unknown Source)
at com.slytechs.library.JNILibrary.register(Unknown Source)
at org.jnetpcap.Pcap.(Unknown Source)
I always have outgoing and incoming IPs defined as 0.0.0.0
How can this be remedied?
how to save this file?i mean with what extension
Hello/Salut,
I’m trying to run this using Intellij, I’ve added the jars and dll,
is there a way to run it using any special command
in Run Configurations in IntelliJ ultimate?
Thanks