I have an int
which contains an IP address in network byte order, which I would like to convert to an InetAddress
object. I see that there is an <
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).
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.
This may work try
public static String intToIp(int i) {
return ((i >> 24 ) & 0xFF) + "." +
((i >> 16 ) & 0xFF) + "." +
((i >> 8 ) & 0xFF) + "." +
( i & 0xFF);
}
public static byte[] int32toBytes(int hex) {
byte[] b = new byte[4];
b[0] = (byte) ((hex & 0xFF000000) >> 24);
b[1] = (byte) ((hex & 0x00FF0000) >> 16);
b[2] = (byte) ((hex & 0x0000FF00) >> 8);
b[3] = (byte) (hex & 0x000000FF);
return b;
}
you can use this function to turn int to bytes;