Programming,  Python

Python script to identify CIDR notation

It’s not uncommon to expect CIDR notation vs an IP address in a script (e.g. one that’s being passed to another API. So the following script is an example of using the re module to identify if an entry is in CIDR or not (since it’s not always obvious how to go about doing so):

import re

def is_cidr(ip_address):
    """
    Returns True if the given IP address is in CIDR notation, False otherwise.
    """
    match = re.match(r"^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/(\d{1,2})$", ip_address)
    if match:
        return True
    else:
        return False

if __name__ == "__main__":
    ip_addresses = ["192.168.1.1", "192.168.1.0/24", "192.168.1.0/25"]
    for ip_address in ip_addresses:
        if is_cidr(ip_address):
            print("The IP address {} is in CIDR notation".format(ip_address))
        else:
            print("The IP address {} is not in CIDR notation".format(ip_address))

The array can easily be changed or filled with a network mask or array of them rather than fixed as they are here – and the output could easily be to call another function rather than to just print output.