BraginiNI
BraginiNI

Reputation: 586

Java: how to convert dec to 32bit int?

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!

Upvotes: 0

Views: 1984

Answers (5)

bestsss
bestsss

Reputation: 12056

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

Upvotes: 1

Ronnie Meier Ramos
Ronnie Meier Ramos

Reputation: 19

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.

Upvotes: 1

Ilya Ivanov
Ilya Ivanov

Reputation: 2499

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

Upvotes: 0

Johan
Johan

Reputation: 20763

Why not get it as a byte array instead?

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500185

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.

Upvotes: 5

Related Questions