Java: how to convert dec to 32bit int?

无人久伴 提交于 2019-12-11 16:26:42

问题


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


来源:https://stackoverflow.com/questions/4984130/java-how-to-convert-dec-to-32bit-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!