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)
InetAddress.getByName
can do DNS lookups. \$\endgroup\$