Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

guava - InetAddress.coerceToInteger returns int instead of long

I have a question about Guava's InetAddress.coerceToInteger method.

According to docs the method:

public static int coerceToInteger(InetAddress ip)

'Returns an integer representing an IPv4 address regardless of whether the supplied argument is an IPv4 address or not. '

But, IPv4 range is of an unsigned 32 bit while Java's int is a signed one - means the returned value can only cover half of the relevant range of IPv4.

Am I missing someone or there is a real problem in the method?

Thanks

like image 359
Ido Avatar asked Dec 26 '22 11:12

Ido


1 Answers

A 32-bit value is a 32-bit value and it can have 2^32 values whether it is signed or unsigned. If you have an address like 192.168.0.1 it will be a negative number, no information is lost. If you turn this into bytes (which are also signed) no information is lost.

BTW: For IPv4 addresses you can use this trick

int address = ip.hashCode();

To treat a 32-bit signed value as a 32-bit unsigned value you can

int address32 = ...
long address = address32 & 0xFFFFFFFFL;

However, you shouldn't need to do this in most situations.

like image 91
Peter Lawrey Avatar answered Mar 03 '23 07:03

Peter Lawrey