UDP extends BasePacket { public byte[] serialize() { byte[] payloadData = null; if (payload != null) { payload.setParent(this); payloadData = payload.serialize(); } this.length = (short) (8 + ((payloadData == null) ? 0 : payloadData.length)); byte[] data = new byte[this.length]; ByteBuffer bb = ByteBuffer.wrap(data); bb.putShort(this.sourcePort); bb.putShort(this.destinationPort); bb.putShort(this.length); bb.putShort(this.checksum); if (payloadData != null) bb.put(payloadData); if (this.parent != null && this.parent instanceof IPv4) ((IPv4)this.parent).setProtocol(IPv4.PROTOCOL_UDP); if (this.checksum == 0) { bb.rewind(); int accumulation = 0; if (this.parent != null && this.parent instanceof IPv4) { IPv4 ipv4 = (IPv4) this.parent; accumulation += ((ipv4.getSourceAddress() >> 16) & 0xffff) + (ipv4.getSourceAddress() & 0xffff); accumulation += ((ipv4.getDestinationAddress() >> 16) & 0xffff) + (ipv4.getDestinationAddress() & 0xffff); accumulation += ipv4.getProtocol() & 0xff; accumulation += this.length & 0xffff; } for (int i = 0; i < this.length / 2; ++i) { accumulation += 0xffff & bb.getShort(); } if (this.length % 2 > 0) { accumulation += (bb.get() & 0xff) << 8; } accumulation = ((accumulation >> 16) & 0xffff) + (accumulation & 0xffff); this.checksum = (short) (~accumulation & 0xffff); bb.putShort(6, this.checksum); } return data; }  short getSourcePort(); UDP setSourcePort(short sourcePort); short getDestinationPort(); UDP setDestinationPort(short destinationPort); short getLength(); short getChecksum(); UDP setChecksum(short checksum); @Override void resetChecksum(); byte[] serialize(); @Override int hashCode(); @Override boolean equals(Object obj); @Override IPacket deserialize(byte[] data, int offset, int length); static Map<Short, Class<? extends IPacket>> decodeMap; static short DHCP_SERVER_PORT; static short DHCP_CLIENT_PORT; }
@Test public void testSerialize() { byte[] expected = new byte[] { 0x45, 0x00, 0x00, 0x1d, 0x56, 0x23, 0x00, 0x00, (byte) 0x80, 0x11, 0x48, 0x7f, (byte) 0xc0, (byte) 0xa8, 0x01, 0x02, 0x0c, (byte) 0x81, (byte) 0xce, 0x02, 0x17, (byte) 0xe1, 0x04, 0x5f, 0x00, 0x09, 0x46, 0x6e, 0x01 }; IPacket packet = new IPv4() .setIdentification((short) 22051) .setTtl((byte) 128) .setSourceAddress("192.168.1.2") .setDestinationAddress("12.129.206.2") .setPayload(new UDP() .setSourcePort((short) 6113) .setDestinationPort((short) 1119) .setPayload(new Data(new byte[] {0x01})) ); byte[] actual = packet.serialize(); assertTrue(Arrays.equals(expected, actual)); }