org.pcap4j.packet.Packet Java Examples

The following examples show how to use org.pcap4j.packet.Packet. 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: PacketUpdater.java    From trex-stateless-gui with Apache License 2.0 7 votes vote down vote up
private Packet fixL3L4Checksums(Packet packet) {
    Packet.Builder builder = packet.getBuilder();
    builder.get(IpV4Packet.Builder.class).correctChecksumAtBuild(true);

    TcpPacket.Builder tcpBuilder = builder.get(TcpPacket.Builder.class);
    if (tcpBuilder != null) {
        tcpBuilder.srcAddr(packet.get(IpV4Packet.class).getHeader().getSrcAddr());
        tcpBuilder.dstAddr(packet.get(IpV4Packet.class).getHeader().getDstAddr());
        tcpBuilder.correctChecksumAtBuild(true);
    }

    UdpPacket.Builder udpBuilder = builder.get(UdpPacket.Builder.class);
    if (udpBuilder != null) {
        udpBuilder.srcAddr(packet.get(IpV4Packet.class).getHeader().getSrcAddr());
        udpBuilder.dstAddr(packet.get(IpV4Packet.class).getHeader().getDstAddr());
        udpBuilder.correctChecksumAtBuild(true);
    }
    return builder.build();
}
 
Example #2
Source File: PacketUpdater.java    From trex-stateless-gui with Apache License 2.0 6 votes vote down vote up
/**
 * Validate packet
 *
 * @param packet
 * @return
 */
public boolean validatePacket(Packet packet) {
    validPacket = true;
    if(packet.get(IpV4Packet.class) == null){
        validPacket = false;
    }else if (defaultSrcAddress == null) {
        return true;
    } else if (!packet.get(IpV4Packet.class).getHeader().getProtocol().name().equals(protocolType)) {
        validPacket = false;
    } else {
        // check src/dst port combination
        currentSrcAddressPort = packet.get(IpV4Packet.class).getHeader().getSrcAddr().getHostAddress() + ":" + getSrcPort(packet);
        currentDstAddressPort = packet.get(IpV4Packet.class).getHeader().getDstAddr().getHostAddress() + ":" + getDstPort(packet);
        if ((!currentSrcAddressPort.equals(defaultSrcAddressPort) && !currentSrcAddressPort.equals(defaultDstAddressPort))
                || (!currentDstAddressPort.equals(defaultSrcAddressPort) && !currentDstAddressPort.equals(defaultDstAddressPort))) {
            validPacket = false;
        }
    }
    return validPacket;
}
 
Example #3
Source File: TCPTun.java    From finalspeed-91yun with GNU General Public License v2.0 6 votes vote down vote up
void onReceiveDataPacket(TcpPacket tcpPacket,TcpHeader tcpHeader,IpV4Header ipV4Header ){
	if(System.currentTimeMillis()-lastSendAckTime>1000){
		int rs=tcpHeader.getSequenceNumber()+tcpPacket.getPayload().getRawData().length;
		if(rs>remoteSequence_max){
			remoteSequence_max=rs;
		}
		Packet ackPacket=PacketUtils.createAck(
				capEnv.local_mac,
				capEnv.gateway_mac,
				localAddress,(short)localPort,
				ipV4Header.getSrcAddr(),tcpHeader.getSrcPort().value(),
				remoteSequence_max, localSequence,getIdent());
		try {
			sendHandle.sendPacket(ackPacket);
		} catch (Exception e) {
			e.printStackTrace();
			
		}
		lastSendAckTime=System.currentTimeMillis();
		lastReceiveDataTime=System.currentTimeMillis();
	}
}
 
Example #4
Source File: TCPTun.java    From finalspeed-91yun with GNU General Public License v2.0 6 votes vote down vote up
void sendData(byte[] data){
	Packet dataPacket=PacketUtils.createDataPacket(capEnv.local_mac,
						capEnv.gateway_mac,
						localAddress,localPort,
						remoteAddress,remotePort,
						localSequence,remoteSequence_max, data, (short) getIdent());
	synchronized (syn_send_data) {
		try {
			sendHandle.sendPacket(dataPacket);
			localSequence+=data.length;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
 
Example #5
Source File: TCPTun.java    From finalspeed-91yun with GNU General Public License v2.0 6 votes vote down vote up
TCPTun(CapEnv capEnv,
		Inet4Address serverAddress,short serverPort,
		MacAddress srcAddress_mac,MacAddress dstAddrress_mac){
	this.capEnv=capEnv;
	sendHandle=capEnv.sendHandle;
	this.remoteAddress=serverAddress;
	this.remotePort=serverPort;
	localAddress=capEnv.local_ipv4;
	localPort=(short)(random.nextInt(64*1024-1-10000)+10000);
	Packet syncPacket=null;
	try {
		syncPacket = PacketUtils.createSync(srcAddress_mac, dstAddrress_mac, localAddress, localPort,serverAddress, serverPort, localStartSequence,getIdent());
		try {
			sendHandle.sendPacket(syncPacket);
			localSequence=localStartSequence+1;
		} catch (Exception e) {
			e.printStackTrace();
		}
	} catch (Exception e1) {
		e1.printStackTrace();
	}
	MLog.println("发送第一次握手 "+" ident "+localIdent);
	MLog.println(""+syncPacket);
	
}
 
Example #6
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 #7
Source File: TrafficProfile.java    From trex-stateless-gui with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param packetBinary
 * @return
 */
public PacketInfo getPacketInfo(String packetBinary) {

    PacketInfo packetInfo = null;

    try {
        byte[] pkt = Base64.decodeBase64(packetBinary);
        Packet packet = EthernetPacket.newPacket(pkt, 0, pkt.length);
        packetInfo = getPacketTypeText(packet);
    } catch (IllegalRawDataException ex) {
        LOG.error("Error reading packet info", ex);
    }

    return packetInfo;

}
 
Example #8
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 #9
Source File: PacketUpdater.java    From trex-stateless-gui with Apache License 2.0 6 votes vote down vote up
/**
 * Update destination IP address
 */
private Packet updateDstAddress(Packet packet) {
    try {
        if (importedProperties.isDestinationEnabled()) {
            Inet4Address modifiedAddress = (Inet4Address) Inet4Address.getByAddress(convertIPToByte(importedProperties.getDstAddress()));
            Packet.Builder builder = packet.getBuilder();
            if (packet.get(IpV4Packet.class).getHeader().getDstAddr().getHostAddress().equals(defaultDstAddress)) {
                builder.get(IpV4Packet.Builder.class).dstAddr(modifiedAddress);
            } else {
                builder.get(IpV4Packet.Builder.class).srcAddr(modifiedAddress);
            }
            packet = builder.build();
        }
    } catch (Exception ex) {
        LOG.error("Error updating destination IP", ex);
    }
    return packet;
}
 
Example #10
Source File: PacketUpdater.java    From trex-stateless-gui with Apache License 2.0 6 votes vote down vote up
/**
 * Update source IP address
 */
private Packet updateSrcAddress(Packet packet) {
    try {
        if (importedProperties.isSourceEnabled()) {
            Inet4Address modifiedAddress = (Inet4Address) Inet4Address.getByAddress(convertIPToByte(importedProperties.getSrcAddress()));
            Packet.Builder builder = packet.getBuilder();
            if (packet.get(IpV4Packet.class).getHeader().getSrcAddr().getHostAddress().equals(defaultSrcAddress)) {
                builder.get(IpV4Packet.Builder.class).srcAddr(modifiedAddress);
            } else {
                builder.get(IpV4Packet.Builder.class).dstAddr(modifiedAddress);
            }
            packet = builder.build();
        }

    } catch (Exception ex) {
        LOG.error("Error updating source IP", ex);
    }
    return packet;
}
 
Example #11
Source File: TCPTun.java    From finalspeed with GNU General Public License v2.0 6 votes vote down vote up
TCPTun(CapEnv capEnv,
       Inet4Address serverAddress, short serverPort,
       MacAddress srcAddress_mac, MacAddress dstAddrress_mac) {
    this.capEnv = capEnv;
    sendHandle = capEnv.sendHandle;
    this.remoteAddress = serverAddress;
    this.remotePort = serverPort;
    localAddress = capEnv.local_ipv4;
    localPort = (short) (random.nextInt(64 * 1024 - 1 - 10000) + 10000);
    Packet syncPacket = null;
    try {
        syncPacket = PacketUtils.createSync(srcAddress_mac, dstAddrress_mac, localAddress, localPort,
                serverAddress, serverPort, localStartSequence, getIdent());
        try {
            sendHandle.sendPacket(syncPacket);
            localSequence = localStartSequence + 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
    } catch (Exception e1) {
        e1.printStackTrace();
    }
    MLog.println("发送第一次握手 " + " ident " + localIdent);
    MLog.println("" + syncPacket);

}
 
Example #12
Source File: TCPTun.java    From NSS with Apache License 2.0 6 votes vote down vote up
void onReceiveDataPacket(TcpPacket tcpPacket, TcpHeader tcpHeader, IpV4Header ipV4Header ){
	if(System.currentTimeMillis()-lastSendAckTime>1000){
		int rs=tcpHeader.getSequenceNumber()+tcpPacket.getPayload().getRawData().length;
		if(rs>remoteSequence_max){
			remoteSequence_max=rs;
		}
		Packet ackPacket=PacketUtils.createAck(
				capEnv.local_mac,
				capEnv.gateway_mac,
				localAddress,(short)localPort,
				ipV4Header.getSrcAddr(),tcpHeader.getSrcPort().value(),
				remoteSequence_max, localSequence,getIdent());
		try {
			sendHandle.sendPacket(ackPacket);
		} catch (Exception e) {
			e.printStackTrace();
			
		}
		lastSendAckTime=System.currentTimeMillis();
		lastReceiveDataTime=System.currentTimeMillis();
	}
}
 
Example #13
Source File: TCPTun.java    From NSS with Apache License 2.0 6 votes vote down vote up
void sendData(byte[] data){
	Packet dataPacket=PacketUtils.createDataPacket(capEnv.local_mac,
						capEnv.gateway_mac,
						localAddress,localPort,
						remoteAddress,remotePort,
						localSequence,remoteSequence_max, data, (short) getIdent());
	synchronized (syn_send_data) {
		try {
			sendHandle.sendPacket(dataPacket);
			localSequence+=data.length;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
 
Example #14
Source File: TCPTun.java    From finalspeed with GNU General Public License v2.0 6 votes vote down vote up
void sendData(byte[] data) {
    Packet dataPacket = PacketUtils.createDataPacket(capEnv.local_mac,
            capEnv.gateway_mac,
            localAddress, localPort,
            remoteAddress, remotePort,
            localSequence, remoteSequence_max, data, getIdent());
    synchronized (syn_send_data) {
        try {
            sendHandle.sendPacket(dataPacket);
            localSequence += data.length;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
 
Example #15
Source File: TCPTun.java    From finalspeed with GNU General Public License v2.0 6 votes vote down vote up
void onReceiveDataPacket(TcpPacket tcpPacket, TcpHeader tcpHeader, IpV4Header ipV4Header) {
    if (System.currentTimeMillis() - lastSendAckTime > 1000) {
        int rs = tcpHeader.getSequenceNumber() + tcpPacket.getPayload().getRawData().length;
        if (rs > remoteSequence_max) {
            remoteSequence_max = rs;
        }
        Packet ackPacket = PacketUtils.createAck(
                capEnv.local_mac,
                capEnv.gateway_mac,
                localAddress, localPort,
                ipV4Header.getSrcAddr(), tcpHeader.getSrcPort().value(),
                remoteSequence_max, localSequence, getIdent());
        try {
            sendHandle.sendPacket(ackPacket);
        } catch (Exception e) {
            e.printStackTrace();

        }
        lastSendAckTime = System.currentTimeMillis();
        lastReceiveDataTime = System.currentTimeMillis();
    }
}
 
Example #16
Source File: TrexEthernetPacketTest.java    From trex-stateless-gui with Apache License 2.0 5 votes vote down vote up
/**
 * Test of buildPacket method, of class TrexEthernetPacket.
 */
@Test
@Parameters({"macSrcAddress", "macDstAddress", "packetLength", "expectedHex"})
public void testEthernetPacketWithoutVlan(String macSrcAddress, String macDstAddress, int packetLength, String expectedHex) throws IOException, IllegalRawDataException {

    LOG.info("------------Testing Ethernet packet");
    // build ethernet packet

    LOG.info("Building Ethernet packet");
    AbstractPacket.AbstractBuilder builder = null;
    TrexEthernetPacket instance = new TrexEthernetPacket();
    instance.setSrcAddr(macSrcAddress);
    instance.setDstAddr(macDstAddress);
    instance.setLength(packetLength);
    instance.buildPacket(builder);

    LOG.info("Encoding packet data");
    
    // Encode packet data
    String encodedBinaryPacket = packetUtil.getEncodedPacket(instance.getPacket().getRawData());
    LOG.info("Decoding packets and returning packet data information");

    // Decode and return packet info
    PacketInfo packetInfo = packetUtil.getPacketInfoData(encodedBinaryPacket);
    LOG.info("Verifying packet data");

    // Assert mac src/destination address
    Assert.assertEquals(macSrcAddress, packetInfo.getSrcMac(), "Invalid MAC source address. ");
    Assert.assertEquals(macDstAddress, packetInfo.getDestMac(), "Invalid MAC destination address. ");

    // Verify packet length
    Packet packet = packetUtil.getPacketFromEncodedString(encodedBinaryPacket);
    Assert.assertEquals(packetLength, packetUtil.getPacketLength(packet), "Invalid Packet length. ");
    
    // Verify packet data
    String packetHex = DatatypeConverter.printHexBinary(packet.getRawData());
    Assert.assertEquals(expectedHex.toLowerCase(), packetHex.toLowerCase(), "Invalid Packet hex. ");

}
 
Example #17
Source File: TrafficProfile.java    From trex-stateless-gui with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param packet
 * @return
 */
public PacketInfo getPacketTypeText(Packet packet) {
    PacketInfo packetInfo = new PacketInfo();

    String packetType = "";
    // Default values for packet info
    packetInfo.setType("Unknown");
    packetInfo.setLength(packet.length());
    if (packet != null) {
        // EthernetPacket
        if (packet.get(EthernetPacket.class) != null) {
            packetType += "Ethernet/";
        }
        // IPPacket
        if (packet.get(IpV4Packet.class) != null) {
            packetType += "IPV4/";
        }
        // TCPPacket
        if (packet.get(TcpPacket.class) != null) {
            packetType += "TCP/";
        }
        // UDPPacket
        if (packet.get(UdpPacket.class) != null) {
            packetType += "UDP";
        }
        if (packetType.endsWith("/")) {
            packetType = packetType.substring(0, packetType.length() - 1);
        }
        packetInfo.setType(packetType);
    }
    return packetInfo;
}
 
Example #18
Source File: TCPTun.java    From NSS with Apache License 2.0 5 votes vote down vote up
TCPTun(CapEnv capEnv,
          Inet4Address serverAddress, short serverPort,
          MacAddress srcAddress_mac, MacAddress dstAddrress_mac){
	this.capEnv=capEnv;
	sendHandle=capEnv.sendHandle;
	this.remoteAddress=serverAddress;
	this.remotePort=serverPort;
	localAddress=capEnv.local_ipv4;
	localPort=(short)(random.nextInt(64*1024-1-10000)+10000);
	Packet syncPacket=null;
	try {
		syncPacket = PacketUtils.createSync(srcAddress_mac, dstAddrress_mac, localAddress, localPort,serverAddress, serverPort, localStartSequence,getIdent());
		try {
			sendHandle.sendPacket(syncPacket);
			localSequence=localStartSequence+1;
		} catch (Exception e) {
			e.printStackTrace();
		}
	} catch (Exception e1) {
		e1.printStackTrace();
	}
	MLog.println("发送第一次握手 "+" ident "+localIdent);
	MLog.println(""+syncPacket);
	
}
 
Example #19
Source File: PacketUpdater.java    From trex-stateless-gui with Apache License 2.0 5 votes vote down vote up
/**
 * Return destination port
 *
 * @param packet
 * @return
 */
private String getDstPort(Packet packet) {
    if (protocolType.equals("TCP")) {
        return packet.get(TcpPacket.class).getHeader().getDstPort().toString();

    } else if (protocolType.equals("UDP")) {
        return packet.get(UdpPacket.class).getHeader().getDstPort().toString();
    }

    return "80";
}
 
Example #20
Source File: PacketUpdater.java    From trex-stateless-gui with Apache License 2.0 5 votes vote down vote up
/**
 * Return source port
 *
 * @param packet
 * @return
 */
private String getSrcPort(Packet packet) {
    if (protocolType.equals("TCP")) {
        return packet.get(TcpPacket.class).getHeader().getSrcPort().toString();

    } else if (protocolType.equals("UDP")) {
        return packet.get(UdpPacket.class).getHeader().getSrcPort().toString();
    }

    return "80";
}
 
Example #21
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 #22
Source File: PacketUpdater.java    From trex-stateless-gui with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize default source/destination address according to first packet
 *
 * @param firstPacket
 */
private void initializeUpdater(Packet firstPacket) {
    defaultSrcAddress = firstPacket.get(IpV4Packet.class).getHeader().getSrcAddr().getHostAddress();
    defaultDstAddress = firstPacket.get(IpV4Packet.class).getHeader().getDstAddr().getHostAddress();
    protocolType = firstPacket.get(IpV4Packet.class).getHeader().getProtocol().name();
    defaultSrcAddressPort = defaultSrcAddress + ":" + getSrcPort(firstPacket);
    defaultDstAddressPort = defaultDstAddress + ":" + getDstPort(firstPacket);
}
 
Example #23
Source File: PacketUpdater.java    From trex-stateless-gui with Apache License 2.0 5 votes vote down vote up
/**
 * Update packet source/destination address
 *
 * @param packet
 * @return
 */
public Packet updatePacketSrcDst(Packet packet) {
    // initialze default src/dst address and protocol type
    if (packet.get(IpV4Packet.class) != null) {
        if (defaultSrcAddress == null && defaultDstAddress == null) {
            initializeUpdater(packet);
        }
        packet = updateSrcAddress(packet);
        packet = updateDstAddress(packet);
        packet = fixL3L4Checksums(packet);
    }

    return packet;
}
 
Example #24
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 #25
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 #26
Source File: PacketUtils.java    From finalspeed-91yun with GNU General Public License v2.0 4 votes vote down vote up
static Packet createDataPacket(
		MacAddress srcAddress_mac,
		MacAddress dstAddrress_mac,
		Inet4Address srcAddress,short srcPort,
		Inet4Address dstAddress,short dstPort,
		int sequence,int ack, byte[] data,short ident){
	Packet p=null;

	TcpPacket.Builder builder_tcp=new TcpPacket.Builder();
	builder_tcp.payloadBuilder(new UnknownPacket.Builder().rawData(data));
	builder_tcp.correctChecksumAtBuild(true);
	builder_tcp.correctLengthAtBuild(true);
	builder_tcp.paddingAtBuild(true);
	builder_tcp.ack(true);
	builder_tcp.acknowledgmentNumber(ack);
	//builder_tcp.checksum(tcpHeader.getChecksum());
	//builder_tcp.dataOffset((byte)8);
	builder_tcp.dstAddr(dstAddress);
	builder_tcp.dstPort(new TcpPort( dstPort,""));
	builder_tcp.fin(false);
	//builder_tcp.options(tcpHeader.getOptions());
	//builder_tcp.padding(tcpHeader.getPadding());
	builder_tcp.psh(false);
	builder_tcp.reserved((byte) 0);
	builder_tcp.rst(false);
	builder_tcp.sequenceNumber(sequence);
	builder_tcp.srcAddr(srcAddress);
	builder_tcp.srcPort(new TcpPort( srcPort,""));
	builder_tcp.syn(false);
	builder_tcp.urg(false);
	//builder_tcp.urgentPointer(tcpHeader.getUrgentPointer());
	builder_tcp.window( window);

	IpV4Packet.Builder builder_ipv4=new IpV4Packet.Builder();
	builder_ipv4.correctChecksumAtBuild(true);
	builder_ipv4.correctLengthAtBuild(true);
	builder_ipv4.dontFragmentFlag(true);
	builder_ipv4.paddingAtBuild(true);
	builder_ipv4.dstAddr(dstAddress);
	builder_ipv4.fragmentOffset( (short)0);
	//builder_ipv4.headerChecksum(ipV4Header.getHeaderChecksum());
	//short identification= Math.abs(random.nextInt(Short.MAX_VALUE));
	//identification=ident;
	builder_ipv4.identification(ident);
	builder_ipv4.ihl((byte) 5);
	builder_ipv4.moreFragmentFlag(false);
	//builder_ipv4.options(ipV4Header.getOptions());
	//builder_ipv4.padding(ipV4Header.getPadding());

	builder_ipv4.protocol(IpNumber.TCP);
	//builder_ipv4.reservedFlag(ipV4Header.getReservedFlag());
	builder_ipv4.srcAddr(srcAddress);
	builder_ipv4.tos(IpV4Rfc1349Tos.newInstance((byte) 0));
	//builder_ipv4.totalLength( 52);
	builder_ipv4.ttl(ttl);
	builder_ipv4.version(IpVersion.IPV4);
	builder_ipv4.payloadBuilder(builder_tcp);

	p = buildIpV4(srcAddress_mac,dstAddrress_mac,builder_ipv4);

	return p;
}
 
Example #27
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 #28
Source File: IpmiPacketReader.java    From ipmi4j with Apache License 2.0 4 votes vote down vote up
protected void processRaw(Packet packet) {
}
 
Example #29
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 #30
Source File: PacketUtils.java    From finalspeed-91yun with GNU General Public License v2.0 4 votes vote down vote up
static Packet createAck(
		MacAddress srcAddress_mac,
		MacAddress dstAddrress_mac,
		Inet4Address srcAddress,short srcPort,
		Inet4Address dstAddress,short dstPort,
		int ack_sequence,int sequence,short ident){

	TcpPacket.Builder builder_tcp=new TcpPacket.Builder();
	//builder_tcp.payloadBuilder(new UnknownPacket.Builder().rawData(new byte[0]));
	builder_tcp.correctChecksumAtBuild(true);
	builder_tcp.correctLengthAtBuild(true);
	builder_tcp.paddingAtBuild(true);
	builder_tcp.ack(true);
	builder_tcp.acknowledgmentNumber(ack_sequence);
	//builder_tcp.checksum(tcpHeader.getChecksum());
	//builder_tcp.dataOffset((byte) 8);
	builder_tcp.dstAddr(dstAddress);
	builder_tcp.dstPort(new TcpPort( dstPort,""));
	//builder_tcp.fin(tcpHeader.getFin());

	builder_tcp.psh(false);
	builder_tcp.reserved((byte) 0);
	builder_tcp.rst(false);
	builder_tcp.sequenceNumber(sequence);
	builder_tcp.srcAddr(srcAddress);
	builder_tcp.srcPort(new TcpPort( srcPort,""));
	builder_tcp.syn(false);
	builder_tcp.urg(false);
	//builder_tcp.urgentPointer(tcpHeader.getUrgentPointer());
	builder_tcp.window( window);

	IpV4Packet.Builder builder_ipv4=new IpV4Packet.Builder();
	builder_ipv4.correctChecksumAtBuild(true);
	builder_ipv4.correctLengthAtBuild(true);
	builder_ipv4.paddingAtBuild(true);
	builder_ipv4.dstAddr(dstAddress);
	builder_ipv4.dontFragmentFlag(true);
	builder_ipv4.fragmentOffset( (short) 0);
	//builder_ipv4.headerChecksum(ipV4Header.getHeaderChecksum());
	//short identification= Math.abs(random.nextInt(Short.MAX_VALUE));
	builder_ipv4.identification(ident);
	builder_ipv4.ihl((byte) 5);
	//builder_ipv4.moreFragmentFlag(ipV4Header.getMoreFragmentFlag());
	//builder_ipv4.options(ipV4Header.getOptions());
	//builder_ipv4.padding(ipV4Header.getPadding());

	builder_ipv4.protocol(IpNumber.TCP);
	//		builder_ipv4.reservedFlag(ipV4Header.getReservedFlag());
	builder_ipv4.srcAddr(srcAddress);
	builder_ipv4.tos(IpV4Rfc1349Tos.newInstance((byte) 0));
	//builder_ipv4.totalLength( 52);
	builder_ipv4.ttl(ttl);
	builder_ipv4.version(IpVersion.IPV4);
	builder_ipv4.payloadBuilder(builder_tcp);
	//
	
	Packet p = buildIpV4(srcAddress_mac,dstAddrress_mac,builder_ipv4);
	//System.out.println("自定义确认 "+" identification "+identification+" ack_sequence "+ack_sequence+" # "+tcpPacket.getHeader());
	return p;

}