开发者

how to convert ipv6 address into integer in Java programming language

how to convert ipv6 address into integer in Java programming l开发者_开发知识库anguage


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.


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();
while(len < 32) {
    str = "0" + str;
    len++;
}
addrStr = new IPAddressString(str);
System.out.println(addrStr.getAddress());

Output:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜