这是我的下面的代码,如果传递任何IPV6地址,我想捕获异常。知道如何在我的代码中完成它吗?
private static boolean validateAnIpAddress(String ipAddr) {
InetAddress address = null;
boolean isIPv4;
try {
address = InetAddress.getByName(ipAddr);
isIPv4 = address.getHostAddress().equals(ipAddr) && address instanceof Inet4Address;
} catch (UnknownHostException e) {
getLogger().log(LogLevel.ERROR, e.getMessage());
//return false;
isIPv4 = false;
}
return isIPv4;
}
答案 0 :(得分:0)
try
{
address = InetAddress.getByName(ipAddr);
boolean isIPv6 = address instanceof Inet6Address;
if (isIPv6)
throw new UnknownHostException("IPv6 Address");
isIPv4 = address.getHostAddress().equals(ipAddr) && address instanceof Inet4Address;
}
通过检查address
是否为Inet6Address
类型,您可以将异常置于try
块内,从而触发catch
阻止。