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 <
Not enough reputation to comment on skaffman's answer so I'll add this as a separate answer.
The solution skaffman proposes is correct with one exception. BigInteger.toByteArray() returns a byte array which could have a leading sign bit.
byte[] bytes = bigInteger.toByteArray();
byte[] inetAddressBytes;
// Should be 4 (IPv4) or 16 (IPv6) bytes long
if (bytes.length == 5 || bytes.length == 17) {
// Remove byte with most significant bit.
inetAddressBytes = ArrayUtils.remove(bytes, 0);
} else {
inetAddressBytes = bytes;
}
InetAddress address = InetAddress.getByAddress(inetAddressBytes);
PS above code uses ArrayUtils from Apache Commons Lang.
public InetAddress intToInetAddress(Integer value) throws UnknownHostException
{
ByteBuffer buffer = ByteBuffer.allocate(32);
buffer.putInt(value);
buffer.position(0);
byte[] bytes = new byte[4];
buffer.get(bytes);
return InetAddress.getByAddress(bytes);
}
Since comments cannot be formatted, let me post the code derived from the comment by @Mr.KevinThomas:
if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) {
ipAddress = Integer.reverseBytes(ipAddress);
}
sReturn = String.format(Locale.US, "%d.%d.%d.%d", (ipAddress >> 24 & 0xff), (ipAddress >> 16 & 0xff), (ipAddress >> 8 & 0xff), (ipAddress & 0xff));
It has been tested on Android.
Tested and working:
int ip = ... ;
String ipStr =
String.format("%d.%d.%d.%d",
(ip & 0xff),
(ip >> 8 & 0xff),
(ip >> 16 & 0xff),
(ip >> 24 & 0xff));
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;
}
}
Using Google Guava:
byte[] bytes =Ints.toByteArray(ipAddress);
InetAddress address = InetAddress.getByAddress(bytes);