How to see if an IP address belongs inside of a range of IPs using CIDR notation?

If you don’t want/can’t add another library (as the IPnetwork one) to your project and just need to deal with IPv4 CIDR ranges, here’s a quick solution to your problem

// true if ipAddress falls inside the CIDR range, example
// bool result = IsInRange("10.50.30.7", "10.0.0.0/8");
private bool IsInRange(string ipAddress, string CIDRmask)
{
    string[] parts = CIDRmask.Split("https://stackoverflow.com/");

    int IP_addr = BitConverter.ToInt32(IPAddress.Parse(ipAddress).GetAddressBytes(), 0);
    int CIDR_addr = BitConverter.ToInt32(IPAddress.Parse(parts[0]).GetAddressBytes(), 0);
    int CIDR_mask = IPAddress.HostToNetworkOrder(-1 << (32 - int.Parse(parts[1])));

    return ((IP_addr & CIDR_mask) == (CIDR_addr & CIDR_mask));
}

the above will allow you to quickly check if a given IPv4 address falls inside a given CIDR range; notice that the above code is barebone, it’s up to you to check if a given IP (string) and CIDR range are correct before feeding them to the function (you may just use the tryparse or whatever…)

Leave a Comment

tech