Description
Background and motivation
IPNetwork currently sits in the Microsoft.AspNetCore.HttpOverrides namespace. However, this class is of great use for applications that don't necessarily run on ASP.NET.
For example, This console tool built on golang is able to de-duplicate IPs and merge CIDRs: https://github.com/zhanhb/cidr-merger.
Currently, if you'd want to implement this in dotnet, you'd either need to import aspnet into your console application, or copy-paste the IPNetwork class into your code.
Additionally, the IPNetwork class could either implement a string constructor or implement IParse<IPNetwork>
, in order to reduce manual parsing from the user's side. Here is an IPHelper
class which implements a simplified parser and helps us visualize a small nuance:
public static class IPHelper
{
public static IPNetwork ParseCidr(string cidr)
{
var splitCidr = cidr.Split('/', 2);
var ip = IPAddress.Parse(splitCidr[0]);
var maskLength = (splitCidr.Length, ip.AddressFamily) switch
{
// if less than 2, the original string is a simple IP address. We must consider it as the full mask.
(< 2, AddressFamily.InterNetwork) => 32,
(< 2, AddressFamily.InterNetworkV6) => 128,
_ => int.Parse(splitCidr[1])
};
return new IPNetwork(ip, maskLength);
}
}
API Proposal
namespace System.Net;
public class IPNetwork
{
public IPNetwork(string cidr) { /* implementation */ }
// same class as Microsoft.AspNetCore.HttpOverrides.IPNetwork here
}
API Usage
namespace System.Net;
var cidr = IPNetwork.Parse("192.168.0.0/16")
Console.WriteLine(cidr.Contains("192.168.0.1"));
Alternative Designs
namespace System.Net;
public class IPNetwork : IParsable<IPNetwork>
{
// Implement IParsable instead of a string constructor...
}
Risks
Current users of the IPNetwork class will have to change their imports. I don't know much about the process of whether that is a breaking change or not, but that's something to consider when applying this change.
Alternatively, we can keep the two classes, but since IPNetwork is such a recent addition, I feel like going the breaking change route may be the fastest way to move forward.