Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CIDR notation and IP range validator pattern

Tags:

java

regex

ip

cidr

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?

like image 540
Maverick Avatar asked Jan 13 '23 11:01

Maverick


1 Answers

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

like image 104
Melih Altıntaş Avatar answered Jan 23 '23 08:01

Melih Altıntaş