1

how to convert ipv6 address into integer in Java programming language

0

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.