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!
解决方案
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()