Java源码示例:org.pcap4j.core.PcapNativeException

示例1
/**
 * @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;
    }

}
 
示例2
@Test(dataProvider = "packetData", dependsOnGroups = {"init"})
public void testTCPProfile(PacketData packetData) throws IOException, InterruptedException, PcapNativeException, NotOpenException, URISyntaxException {
    TrexEthernetPacket ethernetPacket = buildIPV4Packet(packetData);

    // prepare and save yaml data
    LOG.info("Prepare and save Yaml file");
    packetUtil.prepareAndSaveYamlFile(ethernetPacket.getPacket().getRawData(), packetData);

    //Generate pcap files
    LOG.info("Generate Pcap file for " + packetData.getTestFileName() + ".yaml");
    packetUtil.generatePcapFile(packetData.getTestFileName());

    // compare pcaps
    boolean result = packetUtil.comparePcaps(packetData.getTestFileName(), "generated_" + packetData.getTestFileName());
    Assert.assertEquals(result, true, "Invalid generated " + packetData.getTestFileName() + " pcap. ");
}
 
示例3
/**
 * Build IPV4 packet
 *
 * @param packetData
 * @return
 * @throws IOException
 * @throws InterruptedException
 * @throws PcapNativeException
 * @throws NotOpenException
 * @throws java.net.URISyntaxException
 */
public TrexEthernetPacket buildIPV4Packet(PacketData packetData) throws IOException, InterruptedException, PcapNativeException, NotOpenException, URISyntaxException {

    LOG.info("create ethernet packet");
    int packetLength = PacketBuilderHelper.getPacketLength(packetData.getPacketLength().getLengthType(), packetData.getPacketLength().getFrameLength(), packetData.getPacketLength().getMaxLength());
    Payload payload = packetUtil.getPayload(packetData.getPayload());
    TrexEthernetPacket ethernetPacket = packetUtil.prepareEthernetPacket(packetData, packetLength, payload);

    // define VLAN 
    IpV4Packet.Builder ipV4Packet = getIPV4PacketBuilder(PacketBuilderHelper.getIPV4TotalLength(packetData.isTaggedVlan()), packetLength, payload, packetData);
    if (!packetData.isTaggedVlan()) {
        LOG.info("Add IPV4 packet");
        ethernetPacket.buildPacket(ipV4Packet);
    } else {
        packetUtil.addVlanToPacket(ethernetPacket, ipV4Packet);
    }

    return ethernetPacket;
}
 
示例4
@Test(dataProvider = "packetData", dependsOnGroups = {"init"})
public void testIPV4Profile(PacketData packetData) throws IOException, InterruptedException, PcapNativeException, NotOpenException, URISyntaxException {
    TrexEthernetPacket ethernetPacket = buildIPV4Packet(packetData);

    // prepare and save yaml data
    LOG.info("Prepare and save Yaml file");
    packetUtil.prepareAndSaveYamlFile(ethernetPacket.getPacket().getRawData(), packetData);

    //Generate pcap files
    LOG.info("Generate Pcap file for " + packetData.getTestFileName() + ".yaml");
    packetUtil.generatePcapFile(packetData.getTestFileName());

    // compare pcaps
    boolean result = packetUtil.comparePcaps(packetData.getTestFileName(), "generated_" + packetData.getTestFileName());
    Assert.assertEquals(result, true, "Invalid generated " + packetData.getTestFileName() + " pcap. ");
}
 
示例5
@Test(dataProvider = "packetData", dependsOnGroups = {"init"})
public void testUDPProfile(PacketData packetData) throws IOException, InterruptedException, PcapNativeException, NotOpenException, URISyntaxException {
    TrexEthernetPacket ethernetPacket = buildIPV4Packet(packetData);

    // prepare and save yaml data
    LOG.info("Prepare and save Yaml file");
    packetUtil.prepareAndSaveYamlFile(ethernetPacket.getPacket().getRawData(), packetData);

    //Generate pcap files
    LOG.info("Generate Pcap file for " + packetData.getTestFileName() + ".yaml");
    packetUtil.generatePcapFile(packetData.getTestFileName());

    // compare pcaps
    boolean result = packetUtil.comparePcaps(packetData.getTestFileName(), "generated_" + packetData.getTestFileName());
    Assert.assertEquals(result, true, "Invalid generated " + packetData.getTestFileName() + " pcap. ");
}
 
示例6
@Test(dataProvider = "packetData", dependsOnGroups = {"init"})
public void testEthernetProfile(PacketData packetData) throws IOException, InterruptedException, PcapNativeException, NotOpenException, URISyntaxException {
    // create profile
    LOG.info("create ethernet packet");
    int packetLength = PacketBuilderHelper.getPacketLength(packetData.getPacketLength().getLengthType(), packetData.getPacketLength().getFrameLength(), packetData.getPacketLength().getMaxLength());
    Payload payload = packetUtil.getPayload(packetData.getPayload());
    TrexEthernetPacket ethernetPacket = packetUtil.prepareEthernetPacket(packetData, packetLength, payload);

    if (!packetData.isTaggedVlan()) {
        ethernetPacket.buildPacket(null);
    } else {
        packetUtil.addVlanToPacket(ethernetPacket, null);
    }

    // prepare and save yaml data
    LOG.info("Prepare and save Yaml file");
    packetUtil.prepareAndSaveYamlFile(ethernetPacket.getPacket().getRawData(), packetData);

    //Generate pcap files
    LOG.info("Generate Pcap file for " + packetData.getTestFileName() + ".yaml");
    packetUtil.generatePcapFile(packetData.getTestFileName());

    // compare pcaps
    boolean result = packetUtil.comparePcaps(packetData.getTestFileName(), "generated_" + packetData.getTestFileName());
    Assert.assertEquals(result, true, "Invalid generated " + packetData.getTestFileName() + " pcap. ");
}
 
示例7
/**
 * 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();
}
 
示例8
/**
 * Handle select pcap button click event
 * @param event 
 */
@FXML
public void handleSelectPcapBtnClicked(ActionEvent event) {
    if (importedPacketPropertiesView.isValidInputValues()) {
        String loadFolderPath = PreferencesManager.getInstance().getLoadLocation();
        Stage owner = (Stage) wizardViewContainer.getScene().getWindow();
        File pcapFile = FileManager.getSelectedFile("Open Pcap File", "", owner, FileType.PCAP, loadFolderPath, false);
        if (pcapFile != null) {
            try {
                if (importedPacketTableView.setPcapFile(pcapFile)) {
                    wizardViewContainer.getChildren().clear();
                    wizardViewContainer.getChildren().add(importedPacketTableView);
                    updateBtnState(false);
                } else {
                    TrexAlertBuilder.build()
                            .setType(Alert.AlertType.ERROR)
                            .setContent("Invalid Pcap, it should be one flow with IPV4 packets")
                            .getAlert()
                            .showAndWait();
                }
            } catch (PcapNativeException | TimeoutException | NotOpenException ex) {
                TrexAlertBuilder.build()
                        .setType(Alert.AlertType.ERROR)
                        .setTitle("Import error")
                        .setHeader("An error has occurred while attempting to import.")
                        .setContent(ex.getLocalizedMessage())
                        .getAlert()
                        .showAndWait();
            }
        }
    }
}
 
示例9
/**
 * Compare 2 pcap files, return true if equal, otherwise return false
 *
 * @param firstPCAP
 * @param secondPCAP
 * @return
 * @throws PcapNativeException
 * @throws NotOpenException
 */
public boolean comparePcaps(String firstPCAP, String secondPCAP) throws PcapNativeException, NotOpenException, URISyntaxException {
    LOG.info("Comparing pcap files");
    List<String> firstPcapPacketList = getpcapPacketList(getClass().getResource("/pcaps/" + firstPCAP + ".pcap").toURI().getPath());
    List<String> secondPcapPacketList = getpcapPacketList(filePath + secondPCAP + ".pcap");
    if (firstPcapPacketList.size() != secondPcapPacketList.size()) {
        return false;
    }
    boolean equal = true;
    for (int index = 0; index < firstPcapPacketList.size(); index++) {
        equal = equal && (firstPcapPacketList.get(index).equals(secondPcapPacketList.get(index)));
    }
    return equal;
}
 
示例10
/**
 * 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;
}
 
示例11
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());
						}
					}
				}
			}
		}
	}
}
 
示例12
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);
}
 
示例13
public void process_client(CapEnv capEnv, final Packet packet, EthernetHeader ethernetHeader, IpV4Header
        ipV4Header, TcpPacket tcpPacket, boolean client) {

    TcpHeader tcpHeader = tcpPacket.getHeader();
    if (!preDataReady) {
        if (!connectReady) {
            if (tcpHeader.getAck() && tcpHeader.getSyn()) {
                if (tcpHeader.getAcknowledgmentNumber() == (localStartSequence + 1)) {
                    MLog.println("接收第二次握手 " + " ident " + ipV4Header.getIdentification());
                    MLog.println("" + packet);
                    remoteStartSequence = tcpHeader.getSequenceNumber();
                    remoteSequence = remoteStartSequence + 1;
                    remoteSequence_max = remoteSequence;
                    Packet p3 = PacketUtils.createAck(capEnv.local_mac, capEnv.gateway_mac, capEnv.local_ipv4,
                            localPort, remoteAddress, remotePort, remoteSequence, localSequence, getIdent());
                    try {
                        sendHandle.sendPacket(p3);
                        MLog.println("发送第三次握手 " + " ident " + localIdent);
                        MLog.println("" + p3);
                        connectReady = true;

                        byte[] sim = getSimRequestHead(remotePort);
                        sendData(sim);
                        MLog.println("发送请求 " + " ident " + localIdent);
                    } catch (PcapNativeException | NotOpenException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            if (tcpPacket.getPayload() != null) {
                preDataReady = true;
                onReceiveDataPacket(tcpPacket, tcpHeader, ipV4Header);
                MLog.println("接收响应 " + " ident " + ipV4Header.getIdentification());
            }
        }

    } else {
        if (tcpPacket.getPayload() != null) {
            //MLog.println("客户端正式接收数据 "+capClientEnv.vDatagramSocket);
            onReceiveDataPacket(tcpPacket, tcpHeader, ipV4Header);
            TunData td = new TunData();
            td.tun = this;
            td.data = tcpPacket.getPayload().getRawData();
            capEnv.vDatagramSocket.
                    onReceinveFromTun(td);
        }
    }
    if (tcpHeader.getRst()) {
        MLog.println("reset packet " + ipV4Header.getIdentification() + " " + tcpHeader.getSequenceNumber() + " "
                + remoteAddress.getHostAddress() + ":" + remotePort + "->" + localAddress.getHostAddress() + ":" +
                localPort);
    }

}
 
示例14
public IpmiPacketReader(@Nonnull IpmiPacketContext context, @Nonnull File file) throws PcapNativeException {
    this.context = context;
    this.handle = Pcaps.openOffline(file.getAbsolutePath());
}