捕获向量或数据结构中的数据包

时间:2015-08-12 11:45:45

标签: java vector packet-capture jnetpcap

我试图捕获网络数据包并将它们放入Vector中。我无法做到这一点,因为如果我创建一个Vector,它将不会在处理程序中可见。我尝试将Vector公开,但我不能让它工作。我想将数据包存储在Vector中以便稍后进行分析。 这是我的代码:

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 个答案:

没有答案