Search in sources :

Example 1 with Pcap

use of org.jnetpcap.Pcap in project dodo by devhawala.

the class GetXNSPackets method main.

/**
 * Main startup method
 *
 * @param args
 *          ignored
 * @throws IOException
 */
public static void main(String[] args) throws IOException {
    // Will be filled with NICs
    List<PcapIf> alldevs = new ArrayList<PcapIf>();
    // For any error msgs
    StringBuilder errbuf = new StringBuilder();
    /**
     *************************************************************************
     * 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.err.printf("r -> %d\n", r);
    System.err.printf("alldevs.size() = %d\n", alldevs.size());
    System.out.println("Network devices found:");
    PcapIf matchedDev = null;
    int i = 0;
    for (PcapIf device : alldevs) {
        String description = (device.getDescription() != null) ? device.getDescription() : "No description available";
        if ("tap0".equals(description)) {
            System.err.println("** found tap0 by description");
            matchedDev = device;
        }
        if ("tap0".equals(device.getName())) {
            System.err.println("** found tap0 by name");
            matchedDev = device;
        }
        byte[] addr = device.getHardwareAddress();
        String addrLen = "X";
        String sep = "";
        String mac = "";
        if (addr != null) {
            addrLen = "" + addr.length;
            for (byte b : addr) {
                mac = String.format("%s%s%02X", mac, sep, b);
                sep = "-";
            }
        }
        System.out.printf("#%d: %s (%s)[%s] [%s]\n", i++, device.getName(), addrLen, mac, description);
    }
    // We know we have at least 1 device
    PcapIf device = (matchedDev != null) ? matchedDev : alldevs.get(alldevs.size() - 1);
    System.out.printf("\nChoosing '%s' on your behalf:\n", (device.getDescription() != null) ? device.getDescription() : device.getName());
    /**
     *************************************************************************
     * Second we open up the selected device
     *************************************************************************
     */
    // Capture all packets, no trucation
    int snaplen = 64 * 1024;
    // capture all packets
    int flags = Pcap.MODE_PROMISCUOUS;
    // 10 * 1000;           // 10 seconds in millis
    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;
    }
    /**
     *************************************************************************
     * Third we create a packet handler which will receive packets from the
     * libpcap loop.
     *************************************************************************
     */
    PcapPacketHandler<String> jpacketHandler = new PcapPacketHandler<String>() {

        public void nextPacket(PcapPacket packet, String user) {
            if (packet.getByte(12) != (byte) 0x06 || packet.getByte(13) != (byte) 0x00) {
                // System.out.println("packet skipped...");
                return;
            }
            System.out.printf("\n\nReceived packet at %s caplen=%-4d len=%-4d %s\n", new Date(packet.getCaptureHeader().timestampInMillis()), // Length actually captured
            packet.getCaptureHeader().caplen(), // Original length
            packet.getCaptureHeader().wirelen(), // User supplied object
            user);
            // System.out.println(packet);
            int payloadStart = 14;
            int payloadLength = packet.getCaptureHeader().caplen() - payloadStart;
            NetPacket np = new NetPacket(packet.getByteArray(payloadStart, payloadLength));
            IDP idp = new IDP(np);
            PacketType packetType = idp.getPacketType();
            if (packetType == PacketType.SPP) {
                SPP spp = new SPP(idp);
                System.out.printf("%s\n", spp.toString());
                System.out.printf("payload: %s\n", spp.payloadToString());
            } else if (packetType == PacketType.ERROR) {
                Error err = new Error(idp);
                System.out.printf("%s\n", err.toString());
                System.out.printf("payload: %s\n", err.payloadToString());
            } else if (packetType == PacketType.PEX) {
                PEX pex = new PEX(idp);
                System.out.printf("%s\n", pex.toString());
                System.out.printf("payload: %s\n", pex.payloadToString());
            } else {
                System.out.printf("%s\n", np.toString());
                System.out.printf("payload: %s\n", np.payloadToString());
            }
        }
    };
    // JBufferHandler<String> jbufferHandler = new JBufferHandler<String>() {
    // 
    // @Override
    // public void nextPacket(PcapHeader header, JBuffer buffer, String userDate) {
    // buffer.
    // }
    // 
    // }
    /**
     *************************************************************************
     * 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(100000, jpacketHandler, "jNetPcap rocks!");
    /**
     *************************************************************************
     * Last thing to do is close the pcap handle
     *************************************************************************
     */
    pcap.close();
    System.out.printf("GetXNSPackets done\n");
}
Also used : PEX(dev.hawala.xns.level2.PEX) Pcap(org.jnetpcap.Pcap) ArrayList(java.util.ArrayList) NetPacket(dev.hawala.xns.level0.NetPacket) Error(dev.hawala.xns.level2.Error) Date(java.util.Date) SPP(dev.hawala.xns.level2.SPP) IDP(dev.hawala.xns.level1.IDP) PcapPacket(org.jnetpcap.packet.PcapPacket) PacketType(dev.hawala.xns.level1.IDP.PacketType) PcapPacketHandler(org.jnetpcap.packet.PcapPacketHandler) PcapIf(org.jnetpcap.PcapIf)

Example 2 with Pcap

use of org.jnetpcap.Pcap in project dodo by devhawala.

the class NetHubGateway method main.

/**
 * Main startup method
 *
 * @param args
 *          ignored
 */
public static void main(String[] args) {
    boolean printDevs = false;
    String hubHost = "localhost";
    String hubPort = "3333";
    String ifName = "MS LoopBack Driver";
    int argNo = 0;
    // scan command line parameters
    for (int i = 0; i < args.length; i++) {
        if ("-p".equalsIgnoreCase(args[i])) {
            printDevs = true;
        } else if ("-ldd".equalsIgnoreCase(args[i])) {
            logDev = true;
            logDevData = true;
        } else if ("-ld".equalsIgnoreCase(args[i])) {
            logDev = true;
        } else if ("-lhd".equalsIgnoreCase(args[i])) {
            logHub = true;
            logHubData = true;
        } else if ("-lh".equalsIgnoreCase(args[i])) {
            logHub = true;
        } else if (argNo == 0) {
            if (!"=".equals(args[i])) {
                hubHost = args[i];
            }
            argNo++;
        } else if (argNo == 1) {
            if (!"=".equals(args[i])) {
                hubPort = args[i];
            }
            argNo++;
        } else if (argNo == 2) {
            if (!"=".equals(args[i])) {
                ifName = args[i];
            }
            argNo++;
        } else if ("-h".equalsIgnoreCase(args[i])) {
            help();
            return;
        } else {
            System.out.printf("** invalid parameter ignored: '%s'\n", args[i]);
        }
    }
    // get usable hubPort value
    int port = 3333;
    try {
        port = Integer.parseInt(hubPort);
        if (port < 0 || port > 65535) {
            throw new IllegalArgumentException();
        }
    } catch (Exception e) {
        System.out.printf("** invalid hubPort '%s' specified, aborting...\n", hubPort);
        return;
    }
    // PCap data collected
    // the device we shall use
    PcapIf device = null;
    // Will be filled with NICs
    List<PcapIf> alldevs = new ArrayList<PcapIf>();
    // For any error msgs
    StringBuilder errbuf = new StringBuilder();
    // go through the list of PCap 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;
    }
    if (printDevs) {
        System.out.println("Network devices found:");
    }
    int i = 0;
    for (PcapIf ifDev : alldevs) {
        String description = (ifDev.getDescription() != null) ? ifDev.getDescription() : "No description available";
        if (printDevs) {
            System.out.printf("#%d: %s [%s]\n", i++, ifDev.getName(), description);
        }
        if (ifName.equalsIgnoreCase(description)) {
            device = ifDev;
        } else if (ifName.equals(ifDev.getName())) {
            device = ifDev;
        }
    }
    // print device list only?
    if (printDevs) {
        return;
    }
    // the PCap device must exist to continue
    if (device == null) {
        System.out.printf("## ifName '%s' not found, aborting\n", ifName);
        return;
    }
    // open the selected device
    // Capture all packets, no truncation
    int snaplen = 64 * 1024;
    // capture all packets
    int flags = Pcap.MODE_PROMISCUOUS;
    // 5 milliseconds
    int timeout = 5;
    final 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;
    }
    // connect to the NetHub and start receiver thread
    NetHubGateway worker;
    try {
        Socket hubSocket = new Socket(hubHost, port);
        worker = new NetHubGateway(pcap, hubSocket);
        Thread thr = new Thread(worker);
        thr.setDaemon(true);
        thr.start();
    } catch (Exception e) {
        System.err.printf("Unable to open connection to hub (host='%s', port=%d): %s\n", hubHost, port, e.getMessage());
        pcap.close();
        return;
    }
    // packet handler which will receive packets from the libpcap loop forwarding to the NetHub
    PcapPacketHandler<NetHubGateway> jpacketHandler = new PcapPacketHandler<NetHubGateway>() {

        public void nextPacket(PcapPacket packet, NetHubGateway sender) {
            if (packet.getCaptureHeader().wirelen() < 14) {
                // wot? not even the ethernet header...?
                return;
            }
            if (packet.getByte(12) != (byte) 0x06 || packet.getByte(13) != (byte) 0x00) {
                // devLog("non-XNS packet skipped...\n");
                return;
            }
            long srcAddr = 0;
            for (int i = 6; i < 12; i++) {
                srcAddr = (srcAddr << 8) | (packet.getByte(i) & 0xFF);
            }
            if (isExternalHost(srcAddr)) {
                // ignore NetHub packets forwarded through PCap echoed by PCap
                return;
            }
            devLog("\nReceived packet at %s caplen=%-4d len=%-4d size=%d\n", new Date(packet.getCaptureHeader().timestampInMillis()), // Length actually captured
            packet.getCaptureHeader().caplen(), // Original length
            packet.getCaptureHeader().wirelen(), packet.size());
            devLog("%s\n\n", packet.toString());
            if (logDevData) {
                for (int i = 0; i < packet.getCaptureHeader().caplen(); i++) {
                    if ((i % 16) == 0) {
                        System.out.printf("\n 0x%03X: ", i);
                    }
                    System.out.printf(" %02X", packet.getByte(i));
                }
                System.out.printf("\n\n");
            }
            if (!sender.sendPacket(packet)) {
                System.out.printf("## failed to send received packet to hub => shutting down gateway\n");
                pcap.breakloop();
            }
        }
    };
    // enter PCap receiving loop and forward ingoing XNS packets to NetHub
    pcap.loop(Pcap.LOOP_INFINITE, jpacketHandler, worker);
    // done -> close the pcap handle
    pcap.close();
}
Also used : Pcap(org.jnetpcap.Pcap) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Date(java.util.Date) PcapPacket(org.jnetpcap.packet.PcapPacket) PcapPacketHandler(org.jnetpcap.packet.PcapPacketHandler) PcapIf(org.jnetpcap.PcapIf) Socket(java.net.Socket)

Aggregations

ArrayList (java.util.ArrayList)2 Date (java.util.Date)2 Pcap (org.jnetpcap.Pcap)2 PcapIf (org.jnetpcap.PcapIf)2 PcapPacket (org.jnetpcap.packet.PcapPacket)2 PcapPacketHandler (org.jnetpcap.packet.PcapPacketHandler)2 NetPacket (dev.hawala.xns.level0.NetPacket)1 IDP (dev.hawala.xns.level1.IDP)1 PacketType (dev.hawala.xns.level1.IDP.PacketType)1 Error (dev.hawala.xns.level2.Error)1 PEX (dev.hawala.xns.level2.PEX)1 SPP (dev.hawala.xns.level2.SPP)1 IOException (java.io.IOException)1 Socket (java.net.Socket)1