Search code examples
asp.net-coreip-addresscidr

Don't understand IPNetwork.Contains result


I am using the Microsoft.AspNetCore.HttpOverrides.IPNetwork class to check to see if an ip address is in a subnet, but the result is not what I expect

void Main()
{
    var ipnw = new Microsoft.AspNetCore.HttpOverrides.IPNetwork(
                                  IPAddress.Parse("10.10.10.1"), 30);

    // expect these to be true 
    Console.WriteLine(ipnw.Contains(IPAddress.Parse("10.10.10.0")));
    Console.WriteLine(ipnw.Contains(IPAddress.Parse("10.10.10.1")));
    Console.WriteLine(ipnw.Contains(IPAddress.Parse("10.10.10.2")));
    Console.WriteLine(ipnw.Contains(IPAddress.Parse("10.10.10.3")));

    // expect these to be false 
    Console.WriteLine(ipnw.Contains(IPAddress.Parse("10.10.10.4")));
    Console.WriteLine(ipnw.Contains(IPAddress.Parse("10.10.10.5")));
    Console.WriteLine(ipnw.Contains(IPAddress.Parse("10.10.10.6")));
    Console.WriteLine(ipnw.Contains(IPAddress.Parse("10.10.10.7")));

}

I get all false, and I don't understand why. I found a free online site for checking (horrible interface) at https://tehnoblog.org/ip-tools/ip-address-in-cidr-range/, and it shows what I expect...

What am I doing wrong?


Solution

  • Per https://github.com/dotnet/aspnetcore/issues/6674, there is a bug in MS's Contains implementation for the IPNetwork class. The bug has been fixed, but not yet released. As I read it, it expects the address of the CIDR prefix to be the first address that would come from the CIDR prefix/length.

    This means that it doesn't like "10.10.10.1/30" and instead wants "10.10.10.0/30", which does indeed give the expected results.