Build your own Network sniffer

Recently, I ve been developing a tool to monitor the Network Traffic as an assignment. Here, I wish to share my experience with all of you who are interested in building your own Sniffer.

Prerequisites : Java Programming capability, Knowledge on OOP(Object Oriented Programming) basics


My Environment:

I used the libraries specified for Java which is widely available.
I ran my application on Windows XP only. But the libraries can be easily integrated with Linux based systems.
I used NetBeans 6.1 version for development activities. But any other java IDE would do

In setting up the environment, first you need to download Jpcap jar found at http://sourceforge.net/projects/jpcap
Once you download this, you have to add this to your NetBeans project.
It can be done as follows.


















After adding the Jar file to the project, you need to download the WinPCap driver. It can be easily downloaded from http://www.winpcap.org/
It is required to get low level networking access regarding packets.
As for Unix users, there is a version named libpcap which can be used instead.
NOTE: In running built applications, you must allow administrative rights for the programme. Otherwise the driver may not be able to get the necessary information. As for Unix users, you need to run your programme as superuser.

The capturing of packets can be done via a simple set of commands.
For the sake of simplicity, I would just present the most basic commands which would enable you to get up and running. The details of the commands are available at the Jpcap website's tutorial found at http://netresearch.ics.uci.edu/kfujii/jpcap/doc/tutorial/

Write a java file and include the following code on the main method and run the class.



NetworkInterface[] interfaces=JpcapCaptor.getDeviceList();

NOTE: Be careful when using the class for the first time. There is a class with the same name undet java.net package. So, be careful to use jpcap.NetworkInterface[] under the package jpcap.

By using the static method "getDeviceList()" of class "JpcapCaptor", you can get an array of NetworkInterfaces fixed on your computer. The number depends on the computer you have. In my case, I get only one.(The Ethernet interface). But in other computers, you might get more.




Then you need to open a selected interface to start capturing packets.
You can do it in the following manner

JpcapCaptor captor=JpcapCaptor.openDevice(interfaces[0], 65535, true, 20);

Here I'm passing the wanted NetworkInterface as the 1st element of the array returned(In my case I get an array of length 1). Please reffer to the tutorial for precise information on the other parameters.(It does not depend on the machine, so it should work on your machine as well)




captor.processPacket(-1, new PacketPrinter());

The above Line of Code is used in actually capturing the packet. It accepts two paramenters. The first one saying how many packets to capture. Here I have put -1 which would mean infinitely. That means, I keep on capturing packets indefinitely.

The next parameter is an object which needs to implement the interface "PacketReceiver", an interface which is defined by jpcap library.
This interface has one method with the method signature.

public interface PacketReceiver{

public void receivePacket(Packet packet);

}

You need to write a class which implements this interface. Thus you need to implement the method in your class.

Here is my example:

public class PacketPrinter implements PacketReceiver{

public void receivePacket(Packet packet) {
System.out.println(packet);
}
}

My class PacketPrinter just has one method, and I'm implementing the interface here.



Now, compile this code and run the application. You should get the description of all the packets captured on your Standard output.





Filtering packets can be done via the following Line of Code.

NetworkInterface[] interfaces=JpcapCaptor.getDeviceList();
JpcapCaptor captor=JpcapCaptor.openDevice(interfaces[0], 65535, true, 20);
captor.setFilter("tcp", true);
captor.loopPacket(-1, new PacketPrinter());
captor.close();

The above code can be used to filter TCP packets only. If you need only other packets except TCP packets, then you can state "false" as the second parameter above.




I'm sure, this is going to get to up and running with your development as soon as possible. It is up to you to develop a software GUI tool which would satisfy your needs. If you need any help please do not hesitate to mail me.
ruchiram4@gmail.com

The following displays the Tool I prepared. It has special filtering capabilities and Graph to show network traffic.










Due to the request of some, I would like to add some functioning code segment for this.

Please copy the following Classes and try to run the code.



/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ruch.net;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import jpcap.JpcapCaptor;
import jpcap.NetworkInterface;

/**
*
* @author Ruchira
*/
public class SnifferExample {

JpcapCaptor captor;
NetworkInterface[] interfaceList;

//Change this number according to the Network Interface which you wish to Sniff
private static final int interfaceNumber=1;

public static void main(String[] str) {
SnifferExample sniff=new SnifferExample();
sniff.printNetworkInterfaceList();
try {
sniff.capture();
} catch (IOException ex) {
Logger.getLogger(SnifferExample.class.getName()).log(Level.SEVERE, null, ex);
}
}


/**
* Run this method first and it will list out the available network interfaces in your computer
* All of the interfaces will be put into an array (interfaceList)
*/
public void printNetworkInterfaceList() {

interfaceList = JpcapCaptor.getDeviceList();

System.out.println("Number of Network Interfaces Found :"+interfaceList.length);

for (int i = 0; i < interfaceList.length; i++) {
System.out.println("Index :" + i + ", Network Device Name :" + interfaceList[i].name + ", Description :" +
" " + interfaceList[i].description);
}
}

public void capture() throws IOException {

captor=JpcapCaptor.openDevice(interfaceList[interfaceNumber], 65535, true, 20000);
captor.loopPacket(-1, new PacketPrinter());
}
}





/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package ruch.net;

import jpcap.PacketReceiver;
import jpcap.packet.Packet;

/**
*
* @author Ruchira
*/
public class PacketPrinter implements PacketReceiver{

public void receivePacket(Packet pkt) {
System.out.println("Paket :"+pkt.toString());
}

}


Comments

wawa said…
Ruchira
I'm doing a project on exactly the same stuff and its giving me hell, from installations to compiling and i dont seem to get it running properly on my vista machine, ther not may experts of JPcap that would help, i need some expert advice on this if you dont mind and possibly if i could use SOME of your code
ruchira said…
Hi Viniem,

I'm not sure if the WinpCap driver required for the JPCap is compatible with Vista. First try it on a XP machine. I'll bet it will work.
Unknown said…
hi Ruchira,

we are doing the same project, since last four days showing us hell, so at last we found this,we are unable to understand how your adding jar file to library in netbeans, waiting for help...
ruchira said…
Hi Rajkumar,

Actually u don't need to add it as a separate library. U can directly add it as jars to the project.
Expand ur project. Then right click "Libraries", then select "Add JAR/Folder". Then select the jar file which u downloaded. That's it.

However, if u need to know how to create a library, I will describe the procedure roughly.
If you are using NetBeans the procedure to follow is first add the jars as a library to NetBeans.
Then afterwords, you must add the library to the project.
This procedure is taken so that you can add multiple jars together to a single library, and then you can add them to different projects by only adding a single library. It becomes really useful if you are using the same set of jars for multiple projects.
It is to be noted that when you add the library to ur project, it automatically adds the separate jars to the project.

I will roughly display the procedure for adding a library (In NetBeans 6.8)

Go to :

Tools->Libraries

Then click on the button "New Libary..."

Then on the pop-up window, give it any name you like. Leave the type as "Class Library". Select "OK"

Now, on the "Classpath" tab, press "Add Jar/Folder". Now browse to ur downloaded jar and select it.

Additionally you can set the javadoc also. It is not required to work, but will come in handy.

After that, click "OK"

Now, you have added a library to NetBeans.

Now on your project, you must add the library to the project as well.

On your project, expand it's project structure.

Now, right click on "Libraries", select Add Library and select the library we made previously.

I hope this solves ur problem.
therahoolway said…
hi ruchira,
our project is intrusion detection and prevention system and we are trying to store the packets in the file.
we tried to implement it using JpcapWriter, but the jvm crashes after that.
we have come to a dead end, i would really appreciate if you could help.
thanks
anandraj said…
hi ruchira madam
im doing the same project in developing packet capture and analyzing tool and struck with some errors in the middle.

i have MAILED you the work i have done with some code.
can you please help me in running it
and getting output.
i will develop my own graphical tool
GokuL_S_Nair said…
Gokul
haii ruchira
i'm also doing a project relating this same stuff but cant find a class jpcap in package is a problem with the wincap that i have installed or any other softwre in the system.
Unknown said…
hi ruchira
i am doing a project network sniffer
i am able to capture the packets and r displayed on the console view, but i need to do it by gui,so a gui is not opening when i am calling a loopPacket funtion of jpcapcaptor class,but making it a comment the gui is being displayed and the interface list r shown
how could i print it on a gui..
do rply early
ruchira said…
Hi Rohit,

I think the problem is because the GUI gets stuck. Therefore implement the code where to capture packets of a different thread. I think that may be the likely cause.
ANISH said…
Hi Ma'am
I am doing the project on network sniffer..i have written the same code..as u did but the getDeviceList method is not working..i think so..because it doesn't show list with descriptions and then if i enter 0 or 1 then it gives error of arrayoutofboundindex..i have vista..i have installed everything jpcap,winpcap..help me..i have deadline tommorow 12 :00 AM..pls
shubs said…
hi.. i'm trying a very simple code, just to print network devices..

public static void main(String[] args) {
// TODO code application logic here
Sniff sniff=new Sniff();
sniff.printNetworkInterfaceList();
}

public void printNetworkInterfaceList() {

interfaceList = JpcapCaptor.getDeviceList();

System.out.println("Number of Network Interfaces Found :"+interfaceList.length);

for (int i = 0; i < interfaceList.length; i++) {
System.out.println("Index :" + i + ", Network Device Name :" + interfaceList[i].name + ", Description :" +" " + interfaceList[i].description);
}
}

however, this just keeps running without any output..

i'm on win7, using jpcap0.7 and winpcap 4.1.2..
Unknown said…
my jpcap code captures my installed network interface fine, however, when I try to capture packet I get a runtime error from JVM, and yet my code shows me no error. somebody please help I am using netbeans 6.7, jpcap 0.7 and winpcap 4.1.2 all running on windows vista. I have less than five days to submit this school project. Thank you.
ruchira said…
Hi Godwin,
First of all, runtime errors do not show at compile time. Therefore, you need to debug and see what the error is.
Please read the error which is displayed on the console. That will give you more information on what might be missing. I can't directly say what the error is, but I'm sure you can find it yourself :)
pls am not good atall in programming but am writing project on REAL TIME PACKET FILTERING MODULE FOR NETWORK INTRUSION DETECTION SYSTEM. Pls, do i need this code alone or i stil need some other codes?
Rajan said…
Hi Ruchira,
I'm doing some similar project and m stuck in display the graph of packets per sec and also would be glad if you help me to count the number of packets per sec.

Regards,
Rajan
Unknown said…
Hey Ruchira ,I am ranjesh, I am doing the same project having IDS intrusion detection in which we are captureing the packet and anlyzing on basis of Tcp/Udp same as your ,can you plwase hepl me in making our project working
Please mail me your source code so that i can cross check
Unknown said…
Hi, can you like share the source code ? Im doing a similar project and Im geeting an exception error saying that winpcap is not installed . Thanks .
Unknown said…
Hi, can you like share the source code ? Im doing a similar project and Im geeting an exception error saying that winpcap is not installed . Thanks .
hello ruchira,
can u please tell me how to keep graph in jar file i am also doing similar project and i want to show my packets transfer speed and graph like what u did
thank you
Unknown said…
Can you send me the code to show how the linkage is done to show packet details in the table
It is explained in clear way. It is very easy to understand the information.

Get Software Testing Training in Bangalore from Real Time Industry Experts with 100% Placement Assistance in MNC Companies. Book your Free Demo with eTechno Soft Solutions.

Popular posts from this blog

Encrypt and Decrypt Images Using Java

kSoap2 printing request dump