CIDR notation and IP range validator pattern

Maverick picture Maverick · Sep 4, 2013 · Viewed 12.4k times · Source

I have a pattern to validate normal IP addresses, that is :

private static final String PATTERN =
            "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
                    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
                    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
                    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";

And a validate method to check if the input is a valid IP address or not :

private static boolean validate(final String ip){

        Pattern pattern = Pattern.compile(PATTERN);
        Matcher matcher = pattern.matcher(ip);
        return matcher.matches();
    }

But, now I need to add validation for CIDR (e.g. 84.240.40.0/24) notation and IP-range without host (e.g. 172.24.105), I tried many different patterns but not getting something concrete. Any suggestions?

Answer

Melih Altıntaş picture Melih Altıntaş · Sep 4, 2013
Pattern pattern = Pattern.compile("^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\\/(\\d|[1-2]\\d|3[0-2]))?$");
Matcher matcher = pattern.matcher("84.240.40.0/24");
if (matcher.find()) {
    System.out.println(matcher.group());
}

Output:

84.240.40.0/24

this pattern matches IPv4 address and IPv4 CIDR range if you want tomatch only range ,you should remove last question mark