Validate IPv4 address in Java
Try the InetAddressValidator utility class.
Docs here:
http://commons.apache.org/validator/apidocs/org/apache/commons/validator/routines/InetAddressValidator.html
Download here:
http://commons.apache.org/validator/
Please see https://stackoverflow.com/a/5668971/1586965 which uses an apache commons library InetAddressValidator
Or you can use this function -
public static boolean validate(final String ip) {
String PATTERN = "^((0|1\\d?\\d?|2[0-4]?\\d?|25[0-5]?|[3-9]\\d?)\\.){3}(0|1\\d?\\d?|2[0-4]?\\d?|25[0-5]?|[3-9]\\d?)$";
return ip.matches(PATTERN);
}
Pretty simple with Regular Expression (but note this is much less efficient and much harder to read than worpet's answer that uses an Apache Commons Utility)
private static final Pattern PATTERN = Pattern.compile(
"^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");
public static boolean validate(final String ip) {
return PATTERN.matcher(ip).matches();
}
Based on post Mkyong