Wednesday, June 6, 2012

Java Capture packet for a fixed interval using Jnetpcap library

Hi,

Jnetpcap is java library built using libpcap/winpcap. I provides libpcap functionalities using JNI. Sample program are available across internet who capture a certain number of packet. Here is java program who capture packet for certain predefined time interval.


/**
 * Copyright (C) 2008 Sly Technologies, Inc. This library is free software; you
 * can redistribute it and/or modify it under the terms of the GNU Lesser
 * General Public License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version. This
 * library is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details. You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */
package jnetpcap;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.jnetpcap.JBufferHandler;
import org.jnetpcap.Pcap;
import org.jnetpcap.PcapDumper;
import org.jnetpcap.PcapHeader;
import org.jnetpcap.PcapIf;
import org.jnetpcap.nio.JBuffer;
import org.jnetpcap.packet.PcapPacketHandler; 
import java.util.Date;
import org.jnetpcap.packet.PcapPacket; 
import org.jnetpcap.protocol.JProtocol;
/**
 * This example is uses pcap library to capture live packets and dump them to  console.Similar progam can be written to dump the packet to a file. Packets are captured for a certain amount of time and dumped to cosole. After the time interval expires pcap closes
 *
 * @author Mark Bednarczyk
 * @author Sly Technologies, Inc.
 */
public class CapturePacketForCertainTimeInterval {

     public static final int CAPTURE_INTERVAL = 60 * 1000; // 60 seconds in
                                                      

    public static void main(String[] args) {
        List alldevs = new ArrayList(); // Will be filled with
        // NICs
        StringBuilder errbuf = new StringBuilder(); // For any error msgs

        /***************************************************************************
         * First get a list of devices on this system
         **************************************************************************/
        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;
        }
        PcapIf device = alldevs.get(0); // We know we have at least 1 device

        /***************************************************************************
         * Second we open up the selected device
         **************************************************************************/
        int snaplen = 64 * 1024; // Capture all packets, no truncation
        int flags = Pcap.MODE_PROMISCUOUS; // capture all packets
        int timeout = 10*1000; // No timeout, non-interactive traffic
        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;
        }

                       final long interval = System.currentTimeMillis() + CAPTURE_INTERVAL;
               
                System.out.printf("Dump packet for "+(CAPTURE_INTERVAL/1000)+" Secs\n");

                /***************************************************************************
                 * third we create a packet hander which receive packets and break the pcap to end capture after predefined time interval                                 **************************************************************************/
                                            
                                PcapPacketHandler jpacketHandler = new PcapPacketHandler() { 
  
                                public void nextPacket(PcapPacket packet, Pcap pcap) { 
  
                                System.out.printf("Received packet at %s caplen=%-4d len=%-4d\n", 
                                    new Date(packet.getCaptureHeader().timestampInMillis()),  
                                    packet.getCaptureHeader().caplen(),  // Length actually captured 
                                    packet.getCaptureHeader().wirelen() // Original length  
                                                              
                                    );
                               
                                  if (System.currentTimeMillis() > interval) {
                            pcap.breakloop();
                                                        pcap.close();
                                                       
                        }
                
                                     } 
                                }; 

                /***************************************************************************
                 * Fourth we enter the loop.                                  **************************************************************************/
                  pcap.dispatch(Pcap.LOOP_INFINITE,JProtocol.IP4_ID, jpacketHandler,  pcap); 
                             
                             
                                                            
                //dumper.close(); // close out the dumper and flush any unwritten packets
            }
      
}


Note:- pcap.dispatch function may vary depending on OS implementation.  I have run this code on Window XP SP3 using Netbean IDE

please feel free to contact me for any doubt. thanks



3 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Hi,

    I am getting the following errors in red line
    "PcapPacketHandler jpacketHandler = new PcapPacketHandler()"

    error :

    " is not abstract and does not override abstract method nextPacket(PcapPacket,Object) in PcapPacketHandler"
    thanks in advance

    ReplyDelete
    Replies
    1. PcapPacketHandler is an abstract class. You need to implement abstract method nextPacket

      Delete