Avinash
Avinash

Reputation: 13257

how to convert ipv6 address into integer in Java programming language

how to convert ipv6 address into integer in Java programming language

Upvotes: 1

Views: 3351

Answers (2)

Sean F
Sean F

Reputation: 4595

The open-source IPAddress Java library can do the conversion. Disclaimer: I am the project manager of the IPAddress library.

String str = "2001:0db8:85a3:0000:0000:8a2e:0370:7334";
IPAddressString addrStr = new IPAddressString(str);
IPAddress addr  = addrStr.getAddress();
BigInteger value = addr.getValue();
System.out.println(value);

Output:

42540766452641154071740215577757643572

Also note the code works the same for IPv4 addresses.

The library is also capable of doing the reverse conversion, constructing an IPv6Address instance from a BigInteger directly, or from an integer string as shown below. The integer string must be a hexadecimal integer string with 32 digits.

Reverse conversion from a 32 digit hex integer string:

str = value.toString(16);
int len = str.length();
if(len < 32) {
    // 32 zeros
    str = "00000000000000000000000000000000".substring(len) + str; 
}
addrStr = new IPAddressString(str);
System.out.println(addrStr.getAddress());

Output:

2001:db8:85a3::8a2e:370:7334

Upvotes: 3

unwind
unwind

Reputation: 399703

You would have to use a BigInteger, since IPv6 addresses are larger than Java's native integer datatypes support, at 128 bits.

Depending on in which format you have the IPv6 address (raw byte array, hexadecimal string, ...) there might or might not be a BigInteger constructor that's suitable.

Upvotes: 5

Related Questions