Java: convert int to InetAddress

I think that this code is simpler:

static public byte[] toIPByteArray(int addr){
        return new byte[]{(byte)addr,(byte)(addr>>>8),(byte)(addr>>>16),(byte)(addr>>>24)};
    }

static public InetAddress toInetAddress(int addr){
    try {
        return InetAddress.getByAddress(toIPByteArray(addr));
    } catch (UnknownHostException e) {
        //should never happen
        return null;
    }
}

If you're using Google's Guava libraries, InetAddresses.fromInteger does exactly what you want. Api docs are here

If you'd rather write your own conversion function, you can do something like what @aalmeida suggests, except be sure to put the bytes in the right order (most significant byte first).


Tested and working:

int ip  = ... ;
String ipStr = 
  String.format("%d.%d.%d.%d",
         (ip & 0xff),   
         (ip >> 8 & 0xff),             
         (ip >> 16 & 0xff),    
         (ip >> 24 & 0xff));

This should work:

int ipAddress = ....
byte[] bytes = BigInteger.valueOf(ipAddress).toByteArray();
InetAddress address = InetAddress.getByAddress(bytes);

You might have to swap the order of the byte array, I can't figure out if the array will be generated in the correct order.