HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

Validate IP address in Java

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
validateaddressjava

Problem

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-validator's InetAddressValidator. 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)

Solution

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

I'd modify a few small things:

  • The isValid boolean would be unnecesary if you return immediately when you know the return value. (Flattening Arrow Code)



  • (address == null || address.trim().isEmpty()) could be changed to StringUtils.isBlank.



  • According to the Code Conventions for the Java Programming Language if statements always should use braces.



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;
    }
}

Code Snippets

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;
    }
}

Context

StackExchange Code Review Q#14252, answer score: 13

Revisions (0)

No revisions yet.