Represent short form of IPV6 Address
I have an IPv6 address string: 2001:1:0:0:10:0:10:10
开发者_如何学PythonI want to represent it as a short form of IPV6 string: 2001:1::10:0:10:10
Does any one know the java methods to do this?
Since it can be shorten in many different ways in some cases, there is probably no such function in java API. You can manually do:
Inet6Address.getByName("1080::8:800:200C:417A").replaceFirst("(:0)+:", "::");
but I did'n test it very well. There might be some cases this code is wrong.
The open-source IPAddress Java library can provides numerous ways of producing strings for IPv4 and/or IPv6, including the canonical string for IPv6 matching rfc 5952. Disclaimer: I am the project manager of that library.
The method toCanonicalString() produces the canonical string, there is also a method toCompressedString() that is slightly different. With the canonical string a single segment of zero is not compressed, but toCompressedString() will compress such a segment. The method toNormalizedString() will not compress at all.
Using your example 2001:1:0:0:10:0:10:10 and another here is sample code:
IPAddress addr = new IPAddressString("2001:1:0:0:10:0:10:10").getAddress();
System.out.println(addr.toNormalizedString());
System.out.println(addr.toCanonicalString());
System.out.println(addr.toCompressedString());
System.out.println();
addr = new IPAddressString("2001:db8:0:1:1:1:1:1").getAddress();
System.out.println(addr.toNormalizedString());
System.out.println(addr.toCanonicalString());
System.out.println(addr.toCompressedString());
Output:
2001:1:0:0:10:0:10:10
2001:1::10:0:10:10
2001:1::10:0:10:10
2001:db8:0:1:1:1:1:1
2001:db8:0:1:1:1:1:1
2001:db8::1:1:1:1:1
精彩评论