/** * Convert a short integer value into an byte array. * * @param v A short integer value. * @return A converted byte array. * @since Beryllium */ public static byte[] toBytes(short v) { byte[] b = new byte[NUM_OCTETS_SHORT]; setShort(b, 0, v); return b; }
/** * Compute the checksum of the given packet. * * @param ipv4 An {@link Inet4Packet} instance that contains the given * packet. * @param packet A {@link PortPacket} instance. * @param sumOff Offset in bytes to the checksum field. * @return A computed checksum. * @throws VTNException * An error occurred. */ protected static final short computeChecksum( Inet4Packet ipv4, PortPacket<?> packet, int sumOff) throws VTNException { // Serialize the given packet. byte[] data; try { data = packet.serialize(); } catch (Exception e) { // This should never happen. throw new VTNException("Failed to serialize the packet.", e); } // Clear checksum field. NumberUtils.setShort(data, sumOff, (short)0); // Compute checksum. return (short)~computeChecksum(ipv4, data); }
/** * Create a pseudo IPv4 header used for computing TCP/UDP checksum. * * @param proto An IP protocol number. * @param len The number of octets in a payload. * @return A byte array which represents the pseudo IPv4 header. */ public byte[] getHeaderForChecksum(byte proto, short len) { byte[] header = new byte[CKSUM_HEADER_SIZE]; int src = getSourceAddress().getAddress(); int dst = getDestinationAddress().getAddress(); NumberUtils.setInt(header, CKSUM_OFF_SRC, src); NumberUtils.setInt(header, CKSUM_OFF_DST, dst); header[CKSUM_OFF_PROTO] = proto; NumberUtils.setShort(header, CKSUM_OFF_LEN, len); return header; }