int addrByteLength = byteLength(version); int addrBitLength = addrByteLength * Byte.SIZE;
@Override protected DefaultMessage read(ByteBuffer buffer) { if (messageLength.get() == -1) { // check if we can read the message length. if (buffer.remaining() < Integer.BYTES) { return null; } else { messageLength.set(buffer.getInt()); } } if (buffer.remaining() < messageLength.get()) { return null; } long id = buffer.getLong(); Version ipVersion = buffer.get() == 0x0 ? Version.INET : Version.INET6; byte[] octects = new byte[IpAddress.byteLength(ipVersion)]; buffer.get(octects); IpAddress senderIp = IpAddress.valueOf(ipVersion, octects); int senderPort = buffer.getInt(); int messageTypeByteLength = buffer.getInt(); byte[] messageTypeBytes = new byte[messageTypeByteLength]; buffer.get(messageTypeBytes); String messageType = new String(messageTypeBytes, Charsets.UTF_8); int payloadLength = buffer.getInt(); byte[] payloadBytes = new byte[payloadLength]; buffer.get(payloadBytes); // reset for next message messageLength.set(-1); return new DefaultMessage(id, new Endpoint(senderIp, senderPort), messageType, payloadBytes); }
/** * Checks whether the arguments are valid. * * @param version the IP address version * @param value the IP address value stored in a byte array * @param offset the offset in bytes from the beginning of the byte * array with the address * @throws IllegalArgumentException if any of the arguments is invalid */ static void checkArguments(Version version, byte[] value, int offset) { // Check the offset and byte array length int addrByteLength = byteLength(version); if ((offset < 0) || (offset + addrByteLength > value.length)) { String msg; if (value.length < addrByteLength) { msg = "Invalid " + addressName(version) + " address array: array length: " + value.length + ". Must be at least " + addrByteLength; } else { msg = "Invalid " + addressName(version) + " address array: array offset: " + offset + ". Must be in the interval [0, " + (value.length - addrByteLength) + "]"; } throw new IllegalArgumentException(msg); } }
checkpoint(DecoderState.READ_SENDER_IP); case READ_SENDER_IP: byte[] octets = new byte[IpAddress.byteLength(ipVersion)]; buffer.readBytes(octets); senderIp = IpAddress.valueOf(ipVersion, octets);