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!
An IP address simply isn't a
double
value. It's like asking the number for the colour red. It doesn't make sense.What are you really trying to do? What are you hoping to achieve? What's the bigger picture? Whatever it is, I don't think you want to get
double
involved.I can be wrong, but may be the man just wanted to pring hex ip address? ;)
Try this:
Why not get it as a byte array instead?
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()
If you plan to have ipv6 addresses, you should use long instead of integer. You can convert the address into a single long shifting each byte into it.
This will work for both ipv4 and ipv6 addresses.