org.pcap4j.core.NotOpenException Java Examples

The following examples show how to use org.pcap4j.core.NotOpenException. 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: 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 #2
Source File: TCPTest.java    From trex-stateless-gui with Apache License 2.0 6 votes vote down vote up
@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. ");
}
 
Example #3
Source File: AbstractIPV4Test.java    From trex-stateless-gui with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #4
Source File: IPV4Test.java    From trex-stateless-gui with Apache License 2.0 6 votes vote down vote up
@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. ");
}
 
Example #5
Source File: UDPTest.java    From trex-stateless-gui with Apache License 2.0 6 votes vote down vote up
@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. ");
}
 
Example #6
Source File: EthernetTest.java    From trex-stateless-gui with Apache License 2.0 6 votes vote down vote up
@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. ");
}
 
Example #7
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 #8
Source File: ImportPcapWizardController.java    From trex-stateless-gui with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
            }
        }
    }
}
 
Example #9
Source File: PacketUtil.java    From trex-stateless-gui with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #10
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 #11
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 #12
Source File: TCPTun.java    From finalspeed with GNU General Public License v2.0 4 votes vote down vote up
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);
    }

}