1

Im trying to capture network packets and put them in a Vector. Im having trouble doing this because If I create a Vector it wont be visible in the handler. I tried making the Vector public but I cant make it work. I would like to store the packets in a Vector to analyze them later. Here is the code I have :

import java.util.ArrayList;
import java.util.Date;
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 PacketCapturer {
 Vector<PcapPacket> myvector = new Vector<PcapPacket>();
    static PcapPacketHandler<String> jpacketHandler = new PcapPacketHandler<String>() {
        public int norCount = 0, abnCount = 0, otherCount = 0, totalCount = 0;
        public void nextPacket(PcapPacket packet, String user) {
            myvector.addElement(packet);
        }
    };
    public static void main(String[] args) {
        List<PcapIf> alldevs = new ArrayList<PcapIf>();
        StringBuilder errbuf = new StringBuilder();
        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;
        }
        PcapIf device = alldevs.get(1);
        int snaplen = 64 * 1024;
        int flags = Pcap.MODE_PROMISCUOUS;
        int timeout = 1;
        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;
        }

        pcap.loop(-1, jpacketHandler, "");
        pcap.close();
    }
}

0 Answers0