Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Following is the code that I'm currently using to validate the user given ip address (IPV4 and IPV6). It makes use of apache commons-validtor's InetAddressValidtor. However, their function validates only IPV4 address and not IPV6.

public static boolean isValidInetAddress(final String address){
        boolean isValid = false;
        if(address == null || address.trim().isEmpty())
            return isValid;
        if(InetAddressValidator.getInstance().isValid(address)){
            isValid = true;
        } else { //not an IPV4 address, could be IPV6?
            try {
                isValid = InetAddress.getByName(address) instanceof Inet6Address;
            } catch (UnknownHostException ex) {
                isValid = false;
            }
        }
        return isValid;
    }

Is there a better way?

(P.S commons-validator does regex pattern matching for IPV4 address validation)

share|improve this question

1 Answer

up vote 5 down vote accepted

It seems fine if there is not any simpler Java or Apache Commons API.

I'd modify a few small things:

public static boolean isValidInetAddress(final String address) {
    if (StringUtils.isBlank(address)) {
        return false;
    }
    if (InetAddressValidator.getInstance().isValid(address)) {
        return true;
    }

    //not an IPV4 address, could be IPV6?
    try {
        return InetAddress.getByName(address) instanceof Inet6Address;
    } catch (final UnknownHostException ex) {
        return false;
    }
}
share|improve this answer
1  
Thanks for the review! I didn't know about Flatening arrow code! – Senthil Kumar Aug 3 '12 at 11:10

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.