BraginiNI BraginiNI - 6 months ago 24
Java Question

Java: how to convert dec to 32bit int?

How to convert decimal presentation of an ip address to 32bit integer value in java?
I use InetAddress class and getLocalHost method to obtain an IP adress:

public class getIp {

public static void main(String[] args) {
InetAddress ipaddress;

try {
ipaddress=InetAddress.getLocalHost();
System.out.println(ipaddress);
}
catch(UnknownHostException ex)
{
System.out.println(ex.toString());
}


}
}


Than I should convert the result to 32bit integer value and than to string, how do I do that?
Thanks!

Answer

If the IP address is IPv6, it won’t work. Otherwise for the Sun/Oracle implementation and IPv4, you can play dirty: ipaddress.hashCode()works but may break in the future, therefore not recommended.

Otherwise (recommended): int ipv4 = ByteBuffer.wrap(addr.getAddress()).getInt()