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?
views:
822answers:
3
+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
2009-12-24 10:06:10
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
2009-12-24 11:56:36
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
2010-01-21 16:31:04
A:
valli
2009-12-24 10:10:28
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
2009-12-24 10:14:28
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
2010-01-21 15:34:50
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
2010-01-21 16:24:02
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
2010-01-22 12:03:10