get Byte array Of Host Address - Java Network

Java examples for Network:Network Address

Description

get Byte array Of Host Address

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String hostAddress = "java2s.com";
        System.out.println(java.util.Arrays
                .toString(getBytesOfHostAddress(hostAddress)));
    }/*from w  w w  . j  ava2  s  . co m*/

    /**
     * 
     * @param hostAddress
     *            ex:192.168.1.222
     * @return
     */
    public static byte[] getBytesOfHostAddress(String hostAddress) {
        String[] hostAddressParts = hostAddress.split("\\.");

        byte[] bytes = new byte[hostAddressParts.length];
        for (int i = 0; i < hostAddressParts.length; i++) {
            bytes[i] = (byte) Short.parseShort(hostAddressParts[i]);
        }

        final int halfBytesLength = bytes.length / 2;
        for (int i = 0; i < halfBytesLength; i++) {
            final byte b = bytes[i];
            bytes[i] = bytes[bytes.length - 1 - i];
            bytes[bytes.length - 1 - i] = b;
        }
        return bytes;
    }
}

Related Tutorials