TCP/IP Jnetpcap java数据抓包 小demo

jpcap java用于数据抓包的另一大jar包,由于年久失修(不更新)折腾了一下,就被我遗弃了,改用了Jnetpcap,网上资料比较少,基本只能从官网获取一下资料。

 

参考资料:Jnetpcap官网  http://www.jnetpcap.com/?q=examples

 

启动数据捕获,修改下需要捕获的网卡就可

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.packet.format.FormatUtils;
import org.jnetpcap.protocol.lan.Ethernet;
import org.jnetpcap.protocol.network.Ip4;

public class Test {
    public static void main(String[] args) {
        List<PcapIf> alldevs = new ArrayList<PcapIf>(); // 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;
        }

        System.out.println("Network devices found:");

        // 迭代找到的所有网卡
        int i = 0;
        for (PcapIf device : alldevs) {
            String description = (device.getDescription() != null) ? device
                    .getDescription() : "No description available";
            System.out.printf("#%d: %s [%s]\n", i++, device.getName(),
                    description);
        }

        PcapIf device = alldevs.get(2); // We know we have at least 1 device 选择监听那个网卡
        System.out.printf("\nChoosing '%s' on your behalf:\n",
                (device.getDescription() != null) ? device.getDescription()
                        : device.getName());

        /***************************************************************************
         * Second we open up the selected device
         **************************************************************************/
        // 截取长度不超过数据报max65535
        int snaplen = 64 * 1024; // Capture all packets, no trucation 截断
        // 混杂模式
        int flags = Pcap.MODE_PROMISCUOUS; // capture all packets
        int timeout = 10 * 1000; // 10 seconds in millis
        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;
        }

        /***************************************************************************
         * Third we create a packet handler which will receive packets from the
         * libpcap loop.
         **************************************************************************/
            
        //PacketHandler处理
        
        /***************************************************************************
         * Fourth we enter the loop and tell it to capture 10 packets. The loop
         * method does a mapping of pcap.datalink() DLT value to JProtocol ID,
         * which is needed by JScanner. The scanner scans the packet buffer and
         * decodes the headers. The mapping is done automatically, although a
         * variation on the loop method exists that allows the programmer to
         * sepecify exactly which protocol ID to use as the data link type for
         * this pcap interface.
         **************************************************************************/
        pcap.loop(-1, new PacketHandler<String>(), "jNetPcap rocks!");

        /***************************************************************************
         * Last thing to do is close the pcap handle
         **************************************************************************/
        pcap.close();
    }
}

 

捕获的数据处理,设置过滤规则

import java.util.Date;

import org.jnetpcap.packet.PcapPacket;
import org.jnetpcap.packet.PcapPacketHandler;
import org.jnetpcap.protocol.lan.Ethernet;
import org.jnetpcap.protocol.network.Ip4;
import org.jnetpcap.protocol.tcpip.Http;
import org.jnetpcap.protocol.tcpip.Tcp;
import org.jnetpcap.protocol.tcpip.Udp;

public class PacketHandler<T> implements PcapPacketHandler<T> {

    @Override
    public void nextPacket(PcapPacket packet, T user) {

        Http http = new Http();
        if (!packet.hasHeader(http)) {
            return;
        }
        // System.out.printf("Received packet at %s caplen=%-4d len=%-4d %s\n",
        // new Date(packet.getCaptureHeader().timestampInMillis()), packet
        // .getCaptureHeader().caplen(), // Length
        // // actually
        // // captured
        // packet.getCaptureHeader().wirelen(), // Original
        // // length
        // user // User supplied object
        // );
        String contend = packet.toString();
        if (contend.contains("DDDDD")&&contend.contains("upass")) {
            System.out.println(contend);
        }
        // }
        // System.out.println( http.getPacket().toString());

        // System.out.println(contend);

        // String hexdump=packet.toHexdump(packet.size(), false, true,
        // false);

        // byte[] data = FormatUtils.toByteArray(hexdump);

        Ethernet eth = new Ethernet(); // Preallocate our ethernet
                                        // header
        Ip4 ip = new Ip4(); // Preallocat IP version 4 header

        Tcp tcp = new Tcp();

        Udp udp = new Udp();

        // Http http=new Http();
        // if (packet.hasHeader(eth)) {
        // System.out.printf("ethernet.type=%X\n", eth.type());
        // }
        //
        // if (packet.hasHeader(ip)) {
        // System.out.printf("ip.version=%d\n", ip.version());
        // }

    }
}

 

不足之处:截取的数据包数据是像sniff那样,之后就查不到如何只获取右边编码后的数据了

posted @ 2016-08-04 21:32  郁闷紫番薯  阅读(5144)  评论(1编辑  收藏