I've modified my original answer. In Sun's implementation of InetAddress
, the hashCode
method produces the integer representation of the IPv4 address, but as the commenters correctly pointed out, this is not guaranteed by the JavaDoc. Therefore, I decided to use the ByteBuffer
class to calculate the value of the IPv4 address instead.
import java.net.InetAddress;
import java.nio.ByteBuffer;
// ...
try {
// Convert from integer to an IPv4 address
InetAddress foo = InetAddress.getByName("2130706433");
String address = foo.getHostAddress();
System.out.println(address);
// Convert from an IPv4 address to an integer
InetAddress bar = InetAddress.getByName("127.0.0.1");
int value = ByteBuffer.wrap(bar.getAddress()).getInt();
System.out.println(value);
} catch (Exception e) {
e.printStackTrace();
}
The output will be:
127.0.0.1
2130706433