9
\$\begingroup\$

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)

\$\endgroup\$
1
  • \$\begingroup\$ Keep in mind that InetAddress.getByName can do DNS lookups. \$\endgroup\$
    – qerub
    Commented Sep 27, 2013 at 7:03

3 Answers 3

13
\$\begingroup\$

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;
    }
}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Thanks for the review! I didn't know about Flatening arrow code! \$\endgroup\$ Commented Aug 3, 2012 at 11:10
8
\$\begingroup\$

You can use the InetAddressUtils from httpclient library:

/**
 * @param ip the ip
 * @return check if the ip is valid ipv4 or ipv6
 */
private static boolean isValidIp(final String ip) {
    return InetAddressUtils.isIPv4Address(ip) || InetAddressUtils.isIPv6Address(ip);
}
\$\endgroup\$
0
0
\$\begingroup\$

The IPAddress Java library will do it. Disclaimer: I am the project manager.

This library supports IPv4 and IPv6 transparently, so validating either works the same below, and it supports CIDR subnets and other subnet formats as well.

Verify if an address is valid:

    String str = "fe80::6a05:caff:fe3:123%2";
    IPAddressString addrString = new IPAddressString(str);
    try {
         IPAddress addr = addrString.toAddress();
         ...
    } catch(AddressStringException e) {
        //e.getMessage provides validation issue
    }
\$\endgroup\$

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