jsakamoto / ipaddressrange

.NET Class Library for range of IP address, both IPv4 and IPv6.
Mozilla Public License 2.0
370 stars 71 forks source link

Contains not working for bigger subnet #82

Closed matteogarato closed 12 months ago

matteogarato commented 1 year ago

using the documentation:

// "Contains()" method also support IPAddressRange argument.
var rangeD1 = IPAddressRange.Parse("192.168.0.0/16");
var rangeD2 = IPAddressRange.Parse("192.168.10.0/24");
rangeD1.Contains(rangeD2); // is True.

BUT

// "Contains()" method also support IPAddressRange argument.
var rangeD1 = IPAddressRange.Parse("192.168.0.0/16");
var rangeD2 = IPAddressRange.Parse("192.168.1.0/24");
rangeD2.Contains(rangeD1); // is False.

Is it intended behavior or a bug?

jsakamoto commented 1 year ago

@matteogarato It is intended. Because the rangeD2 is overlapping in the rangeD1, but the rangeD2 doesn't contain the rangeD1.

image

Does that make sense?

matteogarato commented 1 year ago

yes it make sense, but logically D2 contains a part of D1 so the contains should return true in my opinion, i propose the edit of Contains like this:

        public bool Contains(IPAddressRange range)
        {
            var rangeBegin = range.Begin.ToUInt32();
            var rangeEnd = range.End.ToUInt32();            
            return Begin <= rangeBegin && rangeEnd <= End || rangeBegin <= Begin && End <= rangeEnd;
        }

it's not a big problem, in my code now i added: rangeD2.Contains(rangeD1) || rangeD1.Contains(rangeD2) to get around the problem