org.pcap4j.packet.EthernetPacket Java Examples

The following examples show how to use org.pcap4j.packet.EthernetPacket. 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: PacketTableView.java    From trex-stateless-gui with Apache License 2.0 6 votes vote down vote up
/**
 * Export stream to pcap file
 */
public void handleExportPcapFile() {
    try {
        Profile p = tabledata.getProfiles().get(streamPacketTableView.getSelectionModel().getSelectedIndex());
        String packetBinary = p.getStream().getPacket().getBinary();

        byte[] pkt = Base64.decodeBase64(packetBinary);
        Packet packet = EthernetPacket.newPacket(pkt, 0, pkt.length);
        File pcapFile = File.createTempFile("temp-file-name", ".pcap");
        PcapHandle handle = Pcaps.openDead(DataLinkType.EN10MB, 65536);
        PcapDumper dumper = handle.dumpOpen(pcapFile.getAbsolutePath());
        Timestamp ts = new Timestamp(0);
        dumper.dump(packet, ts);
        dumper.close();
        handle.close();

        String fileName = p.getName() + ".pcap";
        Window owner = streamPacketTableView.getScene().getWindow();
        FileManager.exportFile("Save Pcap File", fileName, pcapFile, owner, FileType.PCAP);
    } catch (IllegalRawDataException | IOException | PcapNativeException | NotOpenException ex) {
        LOG.error("Error during generate JSON file", ex);
    }
}
 
Example #2
Source File: CapEnv.java    From finalspeed-91yun with GNU General Public License v2.0 6 votes vote down vote up
IpV4Packet getIpV4Packet_pppoe(EthernetPacket packet_eth) throws IllegalRawDataException{
	IpV4Packet ipV4Packet=null;
	byte[] pppData=packet_eth.getPayload().getRawData();
	if(pppData.length>8&&pppData[8]==0x45){
		byte[] b2=new byte[2];
		System.arraycopy(pppData, 4, b2, 0, 2);
		short len=(short) ByteShortConvert.toShort(b2, 0);
		int ipLength=toUnsigned(len)-2;
		byte[] ipData=new byte[ipLength];
		//设置ppp参数
		PacketUtils.pppHead_static[2]=pppData[2];
		PacketUtils.pppHead_static[3]=pppData[3];
		if(ipLength==(pppData.length-8)){
			System.arraycopy(pppData, 8, ipData, 0, ipLength);
			ipV4Packet=IpV4Packet.newPacket(ipData, 0, ipData.length);
		}else {
			MLog.println("长度不符!");
		}
	}
	return ipV4Packet;
}
 
Example #3
Source File: UnixPktDumpService.java    From trex-stateless-gui with Apache License 2.0 5 votes vote down vote up
private EthernetPacket toEtherPkt(byte[] pkt) {
    EthernetPacket ethPkt = null;
    try {
        ethPkt = EthernetPacket.newPacket(pkt, 0, pkt.length);
    } catch (IllegalRawDataException e) {
        LOG.error("Save PCAP. Unable to parse pkt from server.", e);
        return null;
    }
    return ethPkt;
}
 
Example #4
Source File: RecordController.java    From trex-stateless-gui with Apache License 2.0 5 votes vote down vote up
private EthernetPacket toEtherPkt(CapturedPkt pkt) {
    byte[] pktBinary = Base64.getDecoder().decode(pkt.getBinary());
    EthernetPacket ethPkt = null;
    try {
        ethPkt = EthernetPacket.newPacket(pktBinary, 0, pktBinary.length);
    } catch (IllegalRawDataException e) {
        LOG.error("Save PCAP. Unable to parse pkt from server.", e);
        return null;
    }
    return ethPkt;
}
 
Example #5
Source File: TrexEthernetPacket.java    From trex-stateless-gui with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param builder
 */
public void buildPacket(AbstractPacket.AbstractBuilder builder) {

    if (builder == null) {

        this.type = EtherType.getInstance((short) 0xFFFF);
    }

    ethernetBuilder = new EthernetPacket.Builder();
    ethernetBuilder.dstAddr(dstAddr)
            .srcAddr(srcAddr)
            .type(type)
            .payloadBuilder(builder);

    byte[] pad;
    if (builder == null || addPad) {

        if (payload != null) {
            String payloadString = payload.getPayloadType().getPadPayloadString(payload.getPayloadPattern(), 100000);
            pad = new BigInteger(payloadString, 16).toByteArray();
        } else {
            pad = new byte[0];
        }

        ethernetBuilder.paddingAtBuild(false).pad(pad);
        this.packet = ethernetBuilder.build();
        fixPacketLength();
    } else {
        ethernetBuilder.paddingAtBuild(true);
        this.packet = ethernetBuilder.build();
    }
}
 
Example #6
Source File: TrexEthernetPacket.java    From trex-stateless-gui with Apache License 2.0 5 votes vote down vote up
private void fixPacketLength() {
    try {
        EthernetPacket newPacket = packet;
        if (packet.getRawData().length < getLength()) {
            byte[] pad = new byte[getLength() - packet.getRawData().length];
            newPacket = EthernetPacket.newPacket(ArrayUtils.addAll(packet.getRawData(), pad), 0, getLength());
        } else {
            newPacket = EthernetPacket.newPacket(packet.getRawData(), 0, getLength());
        }

        setPacket((EthernetPacket) newPacket);
    } catch (IllegalRawDataException ex) {
        Logger.getLogger(TrexEthernetPacket.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example #7
Source File: PacketHex.java    From trex-stateless-gui with Apache License 2.0 5 votes vote down vote up
/**
 * Handle mouse clicked event
 */
private void handleMouseClickedEvent() {
    TreeTableRow<HexData> selectedRow = (TreeTableRow<HexData>) textField.getParent().getParent();
    if (!selectedRow.getTreeItem().getValue().getOffset().contains("-")) {
        String originalLine = textField.getText();
        String selectedHex = textField.getSelectedText().trim();
        String replacedHex = showDialog(selectedHex);
        if (replacedHex != null) {
            try {
                textField.replaceSelection(replacedHex.toUpperCase());
                String payLoad = hexToASCII(textField.getText());
                TreeTableRow<HexData> hexTable = (TreeTableRow<HexData>) textField.getParent().getParent();
                TreeItem<HexData> selectedItem = hexTable.getTreeItem();
                selectedItem.setValue(new HexData(selectedItem.getValue().getOffset(), textField.getText(), packetParser.formatPayLoad(payLoad)));
                String originalHex = getPacketHexFromList();
                if (selectedItem.getValue().getOffset().contains("-")) {
                    originalHex = originalHex.replaceAll(originalLine.replaceAll(" ", "").replaceAll("\n", ""), textField.getText().replaceAll(" ", "").replaceAll("\n", ""));
                }
                byte[] rawdata = DatatypeConverter.parseHexBinary(originalHex);
                EthernetPacket p = EthernetPacket.newPacket(rawdata, 0, rawdata.length);
                packetParser.parsePacket(p, packetInfo);
                treeRoot.getChildren().clear();
                setData(packetInfo);
            } catch (IllegalRawDataException ex) {
                java.util.logging.Logger.getLogger(PacketHex.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
 
Example #8
Source File: PacketParser.java    From trex-stateless-gui with Apache License 2.0 4 votes vote down vote up
/**
 * Extract packet info
 *
 * @param packet
 * @return
 */
private PacketInfo extractPacketInfo(Packet packet) {

    if (packet != null) {
        packetInfo.setPacketHex(formatHex(DatatypeConverter.printHexBinary(packet.getRawData())));
        packetInfo.setPacketRawData(formatPayLoad(new String(packet.getRawData())));
    }

    // defien whether packet has vlan or not
    if(packet.get(Dot1qVlanTagPacket.class) != null){
        packetInfo.setVlanPacket(true);
    }
    // If the packet has Ethernet
    if (packet.get(EthernetPacket.class) != null) {
        packetInfo.setEthernetHex(getHeaderOffset(packet.get(EthernetPacket.class).getHeader().toHexString().toUpperCase()));
        packetInfo.setEthernetRawData(new String());
        packetInfo.setDestMac(packet.get(EthernetPacket.class).getHeader().getDstAddr().toString());
        packetInfo.setSrcMac(packet.get(EthernetPacket.class).getHeader().getSrcAddr().toString());
    }

    // if the packet has IPV4
    if (packet.get(IpV4Packet.class) != null) {
        packetInfo.setIpv4Hex(getHeaderOffset(packet.get(IpV4Packet.class).getHeader().toHexString().toUpperCase()));
        packetInfo.setIpv4RawData(new String());
        packetInfo.setDestIpv4(packet.get(IpV4Packet.class).getHeader().getDstAddr().getHostAddress());
        packetInfo.setSrcIpv4(packet.get(IpV4Packet.class).getHeader().getSrcAddr().getHostAddress());
    }

    // if the packet has TCP
    if (packet.get(TcpPacket.class) != null) {
        packetInfo.setL4Name("TCP");
        packetInfo.setL4Hex(getHeaderOffset(packet.get(TcpPacket.class).getHeader().toHexString().toUpperCase()));
        packetInfo.setL4RawData(new String());
        if (packet.get(TcpPacket.class).getPayload() != null) {
            packetInfo.setPacketPayLoad(getHeaderOffset(spaceHex(Hex.encodeHexString(packet.get(TcpPacket.class).getPayload().getRawData()))));
        } else {
            packetInfo.setPacketPayLoad(null);
        }
    }

    // if the packet has UDP
    if (packet.get(UdpPacket.class) != null) {
        packetInfo.setL4Name("UDP");
        packetInfo.setL4Hex(getHeaderOffset(packet.get(UdpPacket.class).getHeader().toHexString().toUpperCase()));
        packetInfo.setL4RawData(new String());

        if (packet.get(UdpPacket.class).getPayload() != null) {
            packetInfo.setPacketPayLoad(getHeaderOffset(spaceHex(Hex.encodeHexString(packet.get(UdpPacket.class).getPayload().getRawData()))));
        } else {
            packetInfo.setPacketPayLoad(null);
        }
    }
    return packetInfo;
}
 
Example #9
Source File: PacketUtils.java    From finalspeed-91yun with GNU General Public License v2.0 4 votes vote down vote up
public static Packet buildIpV4(
		MacAddress srcAddress_mac,
		MacAddress dstAddrress_mac,
		IpV4Packet.Builder builder_ipv4){

	org.pcap4j.packet.Packet.Builder builder=null;
	EtherType etherType=null;
	Packet p=null;
	if(ppp){
		etherType=EtherType.PPPOE_SESSION_STAGE;
		
		UnknownPacket.Builder pppBuilder=new UnknownPacket.Builder();
		byte[] ipData=builder_ipv4.build().getRawData();
		
		byte[] lenb=new byte[2];
		ByteShortConvert.toByteArray((short) (ipData.length+2), lenb, 0);
		
		byte[] pppHead=new byte[8];
		System.arraycopy(pppHead_static, 0, pppHead, 0, pppHead.length);
		System.arraycopy(lenb, 0, pppHead, 4, 2);
		
		byte[] newData=new byte[pppHead.length+ipData.length];
		System.arraycopy(pppHead, 0, newData, 0, pppHead.length);
		System.arraycopy(ipData, 0, newData, 8, ipData.length);
		pppBuilder.rawData(newData);
		
		builder=pppBuilder;
	}else {
		etherType=EtherType.IPV4;
		builder=builder_ipv4;
	}
	
	EthernetPacket.Builder etherBuilder = new EthernetPacket.Builder();
	etherBuilder.dstAddr(dstAddrress_mac)
	.srcAddr(srcAddress_mac)
	.type(etherType)
	.payloadBuilder(builder)
	.paddingAtBuild(true);
	
	p = etherBuilder.build();
	
	return p;
}
 
Example #10
Source File: DhcpPacketListener.java    From dhcp4j with Apache License 2.0 4 votes vote down vote up
@Override
public void gotPacket(Packet rawPacket) {
    try {
        LOG.info("Read raw " + rawPacket);
        IpV4Packet ipPacket = rawPacket.get(IpV4Packet.class);
        UdpPacket udpPacket = rawPacket.get(UdpPacket.class);
        byte[] dhcpData = udpPacket.getPayload().getRawData();
        InetSocketAddress remoteAddress = new InetSocketAddress(ipPacket.getHeader().getSrcAddr(), udpPacket.getHeader().getSrcPort().valueAsInt());
        InetSocketAddress localAddress = new InetSocketAddress(ipPacket.getHeader().getDstAddr(), udpPacket.getHeader().getDstPort().valueAsInt());
        DhcpRequestContext context = new DhcpRequestContext(interfaceAddresses, remoteAddress, localAddress);
        DhcpMessage request = decoder.decode(ByteBuffer.wrap(dhcpData));
        LOG.info("Read DHCP " + request);
        DhcpMessage reply = service.getReplyFor(context, request);
        if (reply == null)
            return;
        byte[] replyData = new byte[1536];
        ByteBuffer buffer = ByteBuffer.wrap(replyData);
        encoder.encode(buffer, reply);
        replyData = Arrays.copyOf(replyData, buffer.position());    // Truncate array to writer position.
        UnknownPacket.Builder dhcpBuilder = new UnknownPacket.Builder()
                .rawData(replyData);
        UdpPacket.Builder udpBuilder = new UdpPacket.Builder()
                .payloadBuilder(dhcpBuilder)
                .srcPort(udpPacket.getHeader().getDstPort())
                .dstPort(udpPacket.getHeader().getSrcPort())
                .correctChecksumAtBuild(true)
                .correctLengthAtBuild(true);
        IpV4Packet.Builder ipBuilder = new IpV4Packet.Builder()
                .payloadBuilder(udpBuilder)
                .srcAddr(null) // TODO
                .dstAddr(null) // TODO
                .protocol(IpNumber.UDP)
                .correctChecksumAtBuild(true)
                .correctLengthAtBuild(true)
                .paddingAtBuild(true);
        EthernetPacket.Builder ethernetBuilder = new EthernetPacket.Builder()
                .payloadBuilder(ipBuilder)
                .type(EtherType.IPV4)
                .paddingAtBuild(true);
        Packet replyPacket = ethernetBuilder.build();
        // handle.sendPacket(replyPacket);
    } catch (Exception e) {
        LOG.error("DHCP failed", e);
    }
}
 
Example #11
Source File: DhcpPacketListener.java    From dhcp4j with Apache License 2.0 4 votes vote down vote up
@Override
public void gotPacket(Packet rawPacket) {
    try {
        LOG.info("Read raw " + rawPacket);
        IpV4Packet ipPacket = rawPacket.get(IpV4Packet.class);
        UdpPacket udpPacket = rawPacket.get(UdpPacket.class);
        byte[] dhcpData = udpPacket.getPayload().getRawData();
        InetSocketAddress remoteAddress = new InetSocketAddress(ipPacket.getHeader().getSrcAddr(), udpPacket.getHeader().getSrcPort().valueAsInt());
        InetSocketAddress localAddress = new InetSocketAddress(ipPacket.getHeader().getDstAddr(), udpPacket.getHeader().getDstPort().valueAsInt());
        DhcpRequestContext context = new DhcpRequestContext(interfaceAddresses, remoteAddress, localAddress);
        DhcpMessage request = decoder.decode(ByteBuffer.wrap(dhcpData));
        LOG.info("Read DHCP " + request);
        DhcpMessage reply = service.getReplyFor(context, request);
        if (reply == null)
            return;
        byte[] replyData = new byte[1536];
        ByteBuffer buffer = ByteBuffer.wrap(replyData);
        encoder.encode(buffer, reply);
        replyData = Arrays.copyOf(replyData, buffer.position());    // Truncate array to writer position.
        UnknownPacket.Builder dhcpBuilder = new UnknownPacket.Builder()
                .rawData(replyData);
        UdpPacket.Builder udpBuilder = new UdpPacket.Builder()
                .payloadBuilder(dhcpBuilder)
                .srcPort(udpPacket.getHeader().getDstPort())
                .dstPort(udpPacket.getHeader().getSrcPort())
                .correctChecksumAtBuild(true)
                .correctLengthAtBuild(true);
        IpV4Packet.Builder ipBuilder = new IpV4Packet.Builder()
                .payloadBuilder(udpBuilder)
                .srcAddr(null) // TODO
                .dstAddr(null) // TODO
                .protocol(IpNumber.UDP)
                .correctChecksumAtBuild(true)
                .correctLengthAtBuild(true)
                .paddingAtBuild(true);
        EthernetPacket.Builder ethernetBuilder = new EthernetPacket.Builder()
                .payloadBuilder(ipBuilder)
                .type(EtherType.IPV4)
                .paddingAtBuild(true);
        Packet replyPacket = ethernetBuilder.build();
        // handle.sendPacket(replyPacket);
    } catch (Exception e) {
        LOG.error("DHCP failed", e);
    }
}
 
Example #12
Source File: TrexEthernetPacket.java    From trex-stateless-gui with Apache License 2.0 2 votes vote down vote up
/**
 *
 * @param packet
 */
public void setPacket(EthernetPacket packet) {
    this.packet = packet;
}
 
Example #13
Source File: TrexEthernetPacket.java    From trex-stateless-gui with Apache License 2.0 2 votes vote down vote up
/**
 *
 * @return
 */
public EthernetPacket.Builder getEthernetBuilder() {
    return ethernetBuilder;
}
 
Example #14
Source File: PacketUtil.java    From trex-stateless-gui with Apache License 2.0 2 votes vote down vote up
/**
 * Get packet from encoded string
 *
 * @param encodedBinaryPacket
 * @return packet
 * @throws IllegalRawDataException
 */
public Packet getPacketFromEncodedString(String encodedBinaryPacket) throws IllegalRawDataException {
    byte[] pkt = Base64.decodeBase64(encodedBinaryPacket);
    return EthernetPacket.newPacket(pkt, 0, pkt.length);
}