views:

822

answers:

3

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 InetAddress constructor that takes a byte[], is it necessary to convert the int to a byte[] first, or is there another way?

+4  A: 

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.

skaffman
That does indeed still require swapping the order of the byte array. However, it turns out my input was actually in host order after all!Thanks.
kdt
will not work for addresses in the range 0.0.0.0 - 0.127.255.255 and 255.128.0.0 - 255.255.255.255: `bytes` will have less than 4 elements
Carlos Heuberger
A: 
valli
He was asking for int-to-bytearray, not int-to-string. Also your words "this may work try" makes me think that you just googled blind and copypasted random function? Why?
BalusC
A: 

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.

Dennis Laumen
I don't think an additional leading sign bit will be a problem, but missing bytes if the address is in the range 0.0.0.0 - 0.127.255.255 and 255.128.0.0 - 255.255.255.255
Carlos Heuberger
Sorry, I'm not an expert in this field. Could you elaborate on your comment? I'm afraid I'm missing the point (and could potentially have a bug in my code ;) ).
Dennis Laumen