Extracting packet details using jnetpcap library

4.9k views Asked by At

How to extract protocol field , source ip and destination ip from offline pcap file using jnetpcap library?

1

There are 1 answers

1
Aayush Rathore On BEST ANSWER

For TCP/IP stack: We can get the protocols on the basis of port number of tcp header

Port numbers corresponding to different protocols are given on the following link: http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xml

Getting protocol in jnetpap library ( http://jnetpcap.com ):

PcapPacket packet = //get from somewhere
Tcp tcp = new Tcp();
Ip4 ip = new IP4();
byte[] sIP = new byte[4];
byte[] dIP = new byte[4];
String sourceIP = "";
String destIP = "";

if(packet.hasHeader(ip) && packet.hasHeader(tcp)){
   sIP = packet.getHeader(ip).source();
   sourceIP = org.jnetpcap.packet.format.FormatUtils.ip(sIP);
   dIP = packet.getHeader(ip).destination();
   destIP = org.jnetpcap.packet.format.FormatUtils.ip(dIP);

   System.out.println("*" + sourceIP + "*" + destIP);
   System.out.println("Source IP" + sourceIP);
   System.out.println("Destination IP" + destIP);

   if(tcp.source() == 80){
      System.out.println("HTTP protocol");
   } else if(tcp.source == 23) {
      System.out.println("Telnet protocol");
   }
}