1

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?

jmoreno
  • 12,752
  • 4
  • 60
  • 91
  • Is there any progress sir? – Tiny Wang Sep 16 '21 at 10:02
  • @TinyWang: no, same results and I don’t know if I am doing something wrong or just don’t understand what should be happening. – jmoreno Sep 16 '21 at 10:28
  • I saw you'd edited a [high-vote answer](https://stackoverflow.com/a/1499350/14574199) about how to judge ip address if in a subnet, it doesn't work for you? – Tiny Wang Sep 17 '21 at 08:40

1 Answers1

1

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.

jmoreno
  • 12,752
  • 4
  • 60
  • 91