问题描述
我想知道,是否有一个库我可以用来将长IPv6地址的代表(例如2002:9876:57AB:0000:0000:0000:0000:0001)转换为压缩的IPv6 form(在这种情况下:2002:9876:57AB :: 1)。
I would like to know, whether there is a library which I can use to convert a represenation of a long IPv6 address (such as 2002:9876:57AB:0000:0000:0000:0000:0001) into the compressed IPv6 form (in this case: 2002:9876:57AB::1).
我无法找到这样的库。此库不应使用任何IP Api,不得进行网络连接。
I was not able to find such a library. This library should not use any IP Api, a network connection must not be made.
我已经尝试过
return Inet6Address.getByName(longAdress).toString();
但这只是将4个零替换为1(在本例中为2002:9876:57AB:0 :0:0:0:1)。
but this just replaces the 4 zeros with 1 zero (in this case 2002:9876:57AB:0:0:0:0:1).
任何建议?
推荐答案
public class Ipv6AddressCompressor {
public static String getCompressedAddress(String longAddress) throws UnknownHostException {
longAddress = Inet6Address.getByName(longAddress).getHostAddress();
return longAddress.replaceFirst("(^|:)(0+(:|$)){2,8}", "::");
}
}
这可以保护您免受无效地址的攻击(抛出UnknownHostException) ),并将正确压缩尾随的ipv4地址(即0:0:0:0:0:0:255.255.255.255 - > :: FFFF:FFFF)。这也可以防止已压缩的地址。
This should protect you against invalid addresses (throws the UnknownHostException), and will properly compress trailing ipv4 addresses (i.e. 0:0:0:0:0:0:255.255.255.255 -> ::FFFF:FFFF). This will also protect against already compressed addresses.
这篇关于用于将长IPv6地址转换为压缩形式的Java库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!