Java: how to convert dec to 32bit int?

2019-09-12 06:46发布

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!

5条回答
趁早两清
2楼-- · 2019-09-12 07:23

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楼-- · 2019-09-12 07:26

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());
    }
查看更多
5楼-- · 2019-09-12 07:39

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

查看更多
唯我独甜
6楼-- · 2019-09-12 07:41

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.

查看更多
登录 后发表回答