Description
Background and motivation
Dual stack applications in .NET see connecting IPv4 addresses as IPv4-Mapped IPv6 Addresses. This is problematic when combined with the IPNetworks.Contains function specifying IPv4 networks. E.g. if I want to let the user provide a CIDR string for disallowing access I might write something like:
var disallowed = IPNetwork.Parse(disallowedCidrString);
if (disallowed.Contains(remoteIp)) {
// Deny
} else {
// Allow
}
As the user wants to deny an IPv4 range they write something like "10.0.0.8/8". However this creates problems because it will produce an IPv4 Network that will not match the dual stack Ipv4 mapped ipv6 address.
My interpretation is that the IPv4-Mapped IPv6 Address is actually an IPv4 address and hence should be matchable using a IPv4 IPNetwork. Under this assumption a change to the IPNetwork.Contains implementation as proposed here could prevent such confusions.
ps: I was unsure whether reporting this as an API Suggestion is correct as this does not change the visible API. However as it would be an API Behavior change it seemed to be the most fitting category. Let me know if this was incorrect.
API Proposal
No visible changes except maybe to documentation. My suggestion would be to make the Contains function use IPAddress.IsIPv4MappedToIPv6 to identify that it is actually passed an IPv4 address to make contains behave as expected.
API Usage
var address = IPAddress.Parse("::ffff:10.0.0.12");
var network = IPNetwork.Parse("10.0.0.0/8");
Debug.Assert(network.Contains(address));
Alternative Designs
Handling this as a developer without the proposed change certainly is possible by inspecting the address and network at the point of comparison to work around the existing behavior. However it has to be done carefully to get it right. E.g. simply trying to always match using a IPv6 network would fail if the server configuration was changed to bind only to IPv4.
Risks
Existing usage might in some way expect IPv6 addresses to never get be reported as being contained in IPv4 networks. I cannot think of actual use-case for this though.