Given an ip in numeric format, return a byte array that can be fed to InetAddress. - Java Network

Java examples for Network:IP Address

Description

Given an ip in numeric format, return a byte array that can be fed to InetAddress.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        long ip = 2;
        System.out.println(java.util.Arrays
                .toString(numericIpToByteArray(ip)));
    }//from   w w  w  .ja  va2  s . c  om

    /**
     * Given an ip in numeric format, return a byte array that can be fed to
     * InetAddress.
     * @param ip the ip address in long (such as 3232235780)
     * @return the byte array.
     */
    public static byte[] numericIpToByteArray(long ip) {
        byte[] ipArray = new byte[4];
        ipArray[3] = (byte) (ip & 0xff);
        ipArray[2] = (byte) ((ip >> 8) & 0xff);
        ipArray[1] = (byte) ((ip >> 16) & 0xff);
        ipArray[0] = (byte) ((ip >> 24) & 0xff);
        return ipArray;
    }
}

Related Tutorials