Validate IPv4 address in Java

I want to validate an IPv4 address using Java. It should be written using the dot-decimal notation, so it should have 3 dots ("."), no characters, numbers in between the dots, and numbers should be in a valid range. How should it be done?


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


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

Use Guava's

InetAddresses.isInetAddress(ipStr)