Java: how to convert dec to 32bit int?

2019-09-12 06:38发布

问题:

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!

回答1:

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()



回答2:

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.



回答3:

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.

long ipNumber = 0;
for (Byte aByte : ipaddress.getAddress()) {
    ipNumber = (ipNumber << 8) + aByte;
}

This will work for both ipv4 and ipv6 addresses.



回答4:

Why not get it as a byte array instead?

  • http://download.oracle.com/javase/1.4.2/docs/api/java/net/InetAddress.html#getAddress%28%29


回答5:

I can be wrong, but may be the man just wanted to pring hex ip address? ;)

Try this:

    try {
        InetAddress ipaddress = InetAddress.getLocalHost();
        System.out.println(ipaddress);

        byte[] bytes = ipaddress.getAddress();
        System.out.println(String.format("Hex address: %02x.%02x.%02x.%02x", bytes[0], bytes[1], bytes[2], bytes[3]));
    } catch (UnknownHostException ex) {
        System.out.println(ex.toString());
    }