Ethernet extends BasePacket { public byte[] serialize() { byte[] payloadData = null; if (payload != null) { payload.setParent(this); payloadData = payload.serialize(); } int length = 14 + ((vlanID == VLAN_UNTAGGED) ? 0 : 4) + ((payloadData == null) ? 0 : payloadData.length); if (pad && length < 60) { length = 60; } byte[] data = new byte[length]; ByteBuffer bb = ByteBuffer.wrap(data); bb.put(destinationMACAddress.getBytes()); bb.put(sourceMACAddress.getBytes()); if (vlanID != VLAN_UNTAGGED) { bb.putShort((short) EthType.VLAN_FRAME.getValue()); bb.putShort((short) ((priorityCode << 13) | (vlanID & 0x0fff))); } bb.putShort((short) etherType.getValue()); if (payloadData != null) bb.put(payloadData); if (pad) { Arrays.fill(data, bb.position(), data.length, (byte)0x0); } return data; } Ethernet(); MacAddress getDestinationMACAddress(); Ethernet setDestinationMACAddress(byte[] destinationMACAddress); Ethernet setDestinationMACAddress(MacAddress destinationMACAddress); Ethernet setDestinationMACAddress(String destinationMACAddress); MacAddress getSourceMACAddress(); Ethernet setSourceMACAddress(byte[] sourceMACAddress); Ethernet setSourceMACAddress(MacAddress sourceMACAddress); Ethernet setSourceMACAddress(String sourceMACAddress); byte getPriorityCode(); Ethernet setPriorityCode(byte priorityCode); short getVlanID(); Ethernet setVlanID(short vlanID); EthType getEtherType(); Ethernet setEtherType(EthType etherType); boolean isBroadcast(); boolean isMulticast(); boolean isPad(); Ethernet setPad(boolean pad); byte[] serialize(); @Override IPacket deserialize(byte[] data, int offset, int length); static boolean isMACAddress(String macAddress); static byte[] toMACAddress(String macAddress); static long toLong(byte[] macAddress); static byte[] toByteArray(long macAddress); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static final short TYPE_ARP; static final short TYPE_RARP; static final short TYPE_IPv4; static final short TYPE_LLDP; static final short TYPE_BSN; static final short VLAN_UNTAGGED; static final short DATALAYER_ADDRESS_LENGTH; static Map<Short, Class<? extends IPacket>> etherTypeClassMap; }
@Test public void testSerialize() { Ethernet ethernet = new Ethernet() .setDestinationMACAddress("de:ad:be:ef:de:ad") .setSourceMACAddress("be:ef:de:ad:be:ef") .setEtherType(EthType.of(0)); byte[] expected = new byte[] { (byte) 0xde, (byte) 0xad, (byte) 0xbe, (byte) 0xef, (byte) 0xde, (byte) 0xad, (byte) 0xbe, (byte) 0xef, (byte) 0xde, (byte) 0xad, (byte) 0xbe, (byte) 0xef, 0x0, 0x0 }; assertTrue(Arrays.equals(expected, ethernet.serialize())); }