如果传递IPV6地址,我如何捕获异常

时间:2012-03-28 18:39:59

标签: java ipv6 inetaddress

这是我的下面的代码,如果传递任何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;

     }

1 个答案:

答案 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阻止。