org.pcap4j.core.Pcaps Java Examples

The following examples show how to use org.pcap4j.core.Pcaps. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Sanity.java    From MakeLobbiesGreatAgain with MIT License 6 votes vote down vote up
/** Check the WinPcap lib installation. */
private static boolean checkPCap() {
	try {
		System.out.println("Pcap Info: " + Pcaps.libVersion());
	} catch (Error e) {
		e.printStackTrace();
		message("You MUST have NPCap or WinPCap installed to allow this program to monitor the lobby!"
				+ (Desktop.isDesktopSupported() ? "\nAn installer link will attempt to open." : "Please go to https://www.winpcap.org/ and install it."));
		if (Desktop.isDesktopSupported()) {
			try {
				Desktop.getDesktop().browse(new URL("https://nmap.org/npcap/").toURI());
			} catch (IOException | URISyntaxException e1) {
				e1.printStackTrace();
				message("We couldn't open the URL for you, so go to https://nmap.org/npcap/ and install it!");
			}
		}
		return false;
	}
	return true;
}
 
Example #2
Source File: TrafficProfile.java    From trex-stateless-gui with Apache License 2.0 6 votes vote down vote up
/**
 * @param binaryFile
 * @return Encodes the bytes array of a PCAP File using Base64
 */
public String encodePcapFile(String binaryFile) {

    try {
        PcapHandle handle = Pcaps.openOffline(binaryFile);
        Packet packet = handle.getNextPacketEx();
        handle.close();
        byte[] pkt = packet.getRawData();
        byte[] bytesEncoded = Base64.encodeBase64(pkt);

        return new String(bytesEncoded);
    } catch (IOException | PcapNativeException | TimeoutException | NotOpenException ex) {
        LOG.error("Error encoding pcap file", ex);
        return binaryFile;
    }

}
 
Example #3
Source File: ImportedPacketTableView.java    From trex-stateless-gui with Apache License 2.0 5 votes vote down vote up
/**
 * Parse pcap file to get all streams
 *
 * @param pcapFile
 * @return
 */
public boolean setPcapFile(File pcapFile) throws PcapNativeException,
                                                 TimeoutException,
                                                 NotOpenException {
    List<PacketInfo> packetInfoList = new ArrayList<>();
    PacketUpdater.getInstance().reset();
    PcapHandle handler = Pcaps.openOffline(pcapFile.getAbsolutePath());
    PacketParser parser = new PacketParser();
    Packet packet;
    while (true) {
        try {
            packet = handler.getNextPacketEx();
        } catch (EOFException e) {
            break;
        }
        if (!PacketUpdater.getInstance().validatePacket(packet)) {
            break;
        }
        PacketInfo packetInfo = new PacketInfo();
        packet = PacketUpdater.getInstance().updatePacketSrcDst(packet);
        packetInfo.setPacket(packet);
        packetInfo.setTimeStamp(handler.getTimestamp().getTime());
        parser.parsePacket(packet, packetInfo);
        packetInfoList.add(packetInfo);
    }
    setTableData(packetInfoList);
    return PacketUpdater.getInstance().isValidPacket();
}
 
Example #4
Source File: PacketUtil.java    From trex-stateless-gui with Apache License 2.0 5 votes vote down vote up
/**
 * Read pcap file to get all includes packet
 *
 * @param pcapFile
 * @return
 * @throws PcapNativeException
 * @throws NotOpenException
 */
private List<String> getpcapPacketList(String pcapFile) throws PcapNativeException, NotOpenException {
    PcapHandle handler = Pcaps.openOffline(pcapFile);
    Packet packet = null;
    List<String> packetList = new ArrayList<>();
    while ((packet = handler.getNextPacket()) != null) {
        packetList.add(Hex.encodeHexString(packet.getRawData()));
    }
    return packetList;
}
 
Example #5
Source File: Boot.java    From MakeLobbiesGreatAgain with MIT License 4 votes vote down vote up
public static void main(String[] args) throws UnsupportedLookAndFeelException, AWTException, ClassNotFoundException, InterruptedException,
		FontFormatException, InstantiationException, IllegalAccessException, IOException, PcapNativeException, NotOpenException {
	System.setProperty("jna.nosys", "true");
	if (!Sanity.check()) {
		System.exit(1);
	}
	Settings.init();
	Settings.set("autoload", Settings.get("autoload", "0")); //"autoload" is an ini-only toggle for advanced users.
	setupTray();

	getLocalAddr();
	nif = Pcaps.getDevByAddress(addr);
	if (nif == null) {
		JOptionPane.showMessageDialog(null, "The device you selected doesn't seem to exist. Double-check the IP you entered.", "Error", JOptionPane.ERROR_MESSAGE);
		System.exit(1);
	}

	final int addrHash = addr.hashCode();
	final int snapLen = 65536;
	final PromiscuousMode mode = PromiscuousMode.NONPROMISCUOUS;
	final int timeout = 0;
	handle = nif.openLive(snapLen, mode, timeout);
	handle.setFilter("udp && less 150", BpfProgram.BpfCompileMode.OPTIMIZE);

	ui = new Overlay();

	while (running) {
		final Packet packet = handle.getNextPacket();

		if (packet != null) {
			final IpV4Packet ippacket = packet.get(IpV4Packet.class);

			if (ippacket != null) {
				final UdpPacket udppack = ippacket.get(UdpPacket.class);

				if (udppack != null && udppack.getPayload() != null) {
					final int srcAddrHash = ippacket.getHeader().getSrcAddr().hashCode();
					final int dstAddrHash = ippacket.getHeader().getDstAddr().hashCode();
					final int payloadLen = udppack.getPayload().getRawData().length;

					if (active.containsKey(srcAddrHash) && srcAddrHash != addrHash) {
						if (active.get(srcAddrHash) != null && payloadLen == 68  //Packets are STUN related: 56 is request, 68 is response
								&& dstAddrHash == addrHash) {
							ui.setPing(ippacket.getHeader().getSrcAddr(), handle.getTimestamp().getTime() - active.get(srcAddrHash).getTime());
							active.put(srcAddrHash, null); //No longer expect ping
						}
					} else {
						if (payloadLen == 56 && srcAddrHash == addrHash) {
							active.put(ippacket.getHeader().getDstAddr().hashCode(), handle.getTimestamp());
						}
					}
				}
			}
		}
	}
}
 
Example #6
Source File: Boot.java    From MakeLobbiesGreatAgain with MIT License 4 votes vote down vote up
public static void getLocalAddr() throws InterruptedException, PcapNativeException, UnknownHostException, SocketException,
		ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
	if (Settings.getDouble("autoload", 0) == 1) {
		addr = InetAddress.getByName(Settings.get("addr", ""));
		return;
	}

	UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
	final JFrame frame = new JFrame("Network Device");
	frame.setFocusableWindowState(true);

	final JLabel ipLab = new JLabel("Select LAN IP obtained from Network Settings:", JLabel.LEFT);
	final JComboBox<String> lanIP = new JComboBox<String>();
	final JLabel lanLabel = new JLabel("If your device IP isn't in the dropdown, provide it below.");
	final JTextField lanText = new JTextField(Settings.get("addr", ""));

	ArrayList<InetAddress> inets = new ArrayList<InetAddress>();

	for (PcapNetworkInterface i : Pcaps.findAllDevs()) {
		for (PcapAddress x : i.getAddresses()) {
			InetAddress xAddr = x.getAddress();
			if (xAddr != null && x.getNetmask() != null && !xAddr.toString().equals("/0.0.0.0")) {
				NetworkInterface inf = NetworkInterface.getByInetAddress(x.getAddress());
				if (inf != null && inf.isUp() && !inf.isVirtual()) {
					inets.add(xAddr);
					lanIP.addItem((lanIP.getItemCount() + 1) + " - " + inf.getDisplayName() + " ::: " + xAddr.getHostAddress());
					System.out.println("Found: " + lanIP.getItemCount() + " - " + inf.getDisplayName() + " ::: " + xAddr.getHostAddress());
				}
			}
		}
	}

	if (lanIP.getItemCount() == 0) {
		JOptionPane.showMessageDialog(null, "Unable to locate devices.\nPlease try running the program in Admin Mode.\nIf this does not work, you may need to reboot your computer.",
				"Error", JOptionPane.ERROR_MESSAGE);
		System.exit(1);
	}
	lanIP.setFocusable(false);
	final JButton start = new JButton("Start");
	start.addActionListener(e -> {
		try {
			if (lanText.getText().length() >= 7 && !lanText.getText().equals("0.0.0.0")) { // 7 is because the minimum field is 0.0.0.0
				addr = InetAddress.getByName(lanText.getText());
				System.out.println("Using IP from textfield: " + lanText.getText());
			} else {
				addr = inets.get(lanIP.getSelectedIndex());
				System.out.println("Using device from dropdown: " + lanIP.getSelectedItem());
			}
			Settings.set("addr", addr.getHostAddress().replaceAll("/", ""));
			frame.setVisible(false);
			frame.dispose();
		} catch (UnknownHostException e1) {
			e1.printStackTrace();
		}
	});

	frame.setLayout(new GridLayout(5, 1));
	frame.add(ipLab);
	frame.add(lanIP);
	frame.add(lanLabel);
	frame.add(lanText);
	frame.add(start);
	frame.setAlwaysOnTop(true);
	frame.pack();
	frame.setLocationRelativeTo(null);
	frame.setVisible(true);
	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

	while (frame.isVisible())
		Thread.sleep(10);
}
 
Example #7
Source File: IpmiPacketReader.java    From ipmi4j with Apache License 2.0 4 votes vote down vote up
public IpmiPacketReader(@Nonnull IpmiPacketContext context, @Nonnull File file) throws PcapNativeException {
    this.context = context;
    this.handle = Pcaps.openOffline(file.getAbsolutePath());
}