1、获取IPV6地址
public static String getLocalIPv6Address() throws IOException {
InetAddress inetAddress = null;
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
.getNetworkInterfaces();
String ipAddr = null;
while (networkInterfaces.hasMoreElements()) {
Enumeration<InetAddress> inetAds = networkInterfaces.nextElement()
.getInetAddresses();
while (inetAds.hasMoreElements()) {
inetAddress = inetAds.nextElement();
//Check if it's ipv6 address and reserved address
if (inetAddress instanceof Inet6Address
&& inetAddress.isSiteLocalAddress()
&& !inetAddress.isLoopbackAddress()
&& !isReservedAddr(inetAddress)) {
ipAddr = inetAddress.getHostAddress();
int index = ipAddr.indexOf('%');
if (index > 0) {
ipAddripAddr = ipAddr.substring(0, index);
}
}
}
}
return ipAddr;
}
/**
* Check if it's "local address" or "link local address" or
* "loopbackaddress"
*
* @param ip address
*
* @return result
*/
private static boolean isReservedAddr(InetAddress inetAddr) {
if (inetAddr.isAnyLocalAddress() || inetAddr.isLinkLocalAddress()
|| inetAddr.isLoopbackAddress()) {
return true;
}
return false;
}
2、IP地址校验
public static boolean isIPV6Format(String ip) {
ip = ip.trim();
//in many cases such as URLs, IPv6 addresses are wrapped by []
if(ip.substring(0, 1).equals("[") && ip.substring(ip.length()-1).equals("]"))
ip = ip.substring(1, ip.length()-1);
return (1 < Pattern.compile(":").split(ip).length)
//a valid IPv6 address should contains no less than 1,
//and no more than 7 “:” as separators
&& (Pattern.compile(":").split(ip).length <= 8)
//the address can be compressed, but “::” can appear only once
&& (Pattern.compile("::").split(ip).length <= 2)
//if a compressed address
&& (Pattern.compile("::").split(ip).length == 2)
//if starts with “::” – leading zeros are compressed
? (((ip.substring(0, 2).equals("::"))
? Pattern.matches("^::([\\da-f]{1,4}(:)){0,4}(([\\da-f]{1,4}(:)[\\da-f]{1,4})|([\\da-f]{1,4})|((\\d{1,3}.){3}\\d{1,3}))", ip) : Pattern.matches("^([\\da-f]{1,4}(:|::)){1,5}(([\\da-f]{1,4}(:|::)[\\da-f]{1,4})|([\\da-f]{1,4})|((\\d{1,3}.){3}\\d{1,3}))", ip)))
//if ends with "::" - ending zeros are compressed
: ((ip.substring(ip.length()-2).equals("::"))
? Pattern.matches("^([\\da-f]{1,4}(:|::)){1,7}", ip)
: Pattern.matches("^([\\da-f]{1,4}:){6}(([\\da-f]{1,4} :[\\da-f]{1,4})|((\\d{1,3}.){3}\\d{1,3}))", ip));
}
}