Checks that the value is a valid IP address or a valid CIDR.

    Returns the specified value.

    If 'return_as_cidr' is set then the return value will always be in the form
    of a CIDR, even if a plain IP address was specified.

def check_valid_ip_or_cidr(val, return_as_cidr=False):
    """
    Checks that the value is a valid IP address or a valid CIDR.

    Returns the specified value.

    If 'return_as_cidr' is set then the return value will always be in the form
    of a CIDR, even if a plain IP address was specified.

    """
    is_ip = True
    if "/" in val:
        ip_check(val, netmask_expected=True)
        is_ip = False
    else:
        ip_check(val, netmask_expected=False)

    if return_as_cidr and is_ip:
        # Convert a plain IP to a CIDR
        if val == "0.0.0.0":
            # Special case for the default route
            val = "0.0.0.0/0"
        else:
            val = "%s/32" % val

    try:
        ipaddress.IPv4Network(unicode(val))
    except Exception as e:
        raise ArgsError("Not a valid network: %s" % str(e))

    return val