0

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!

BraginiNI
  • 576
  • 1
  • 16
  • 30
  • @Marcelo Cantos, double can hold IPv6 [and before you ask how would you use it: Double.doubleToRawLongBits(d)]. But it looks geekish to keep IP addr in double, does it not? – bestsss Feb 13 '11 at 13:01
  • @bestsss: No, double (and long) have only 64 bits, IPv6 addresses have 128 bits each. – Paŭlo Ebermann Feb 13 '11 at 14:06
  • @Paŭlo Ebermann, sure it is. You need more than a single double, it was supposed to be a joke; okie, didn't work well, i guess. – bestsss Feb 13 '11 at 14:14

5 Answers5

5

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
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()

Martin
  • 2,573
  • 28
  • 22
bestsss
  • 11,796
  • 3
  • 53
  • 63
1

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.

0

Why not get it as a byte array instead?

Johan
  • 20,067
  • 28
  • 92
  • 110
0

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());
    }
Ilya Ivanov
  • 2,379
  • 1
  • 21
  • 24