Description
Background and motivation
We've been using a custom IPAddressRange in our project, but this seems like a general-purpose concern. Looking across internal code bases at Microsoft, we've found dozens of similar implementations of this type, reinforcing the notion that this is general-purpose and should be in the framework.
API Proposal
Edit by @antonfirsov: Added implementations for ISpanFormattable
and IParsable<IPSubnet>
, harmonized naming of method arguments to match current BCL standards.
namespace System.Net;
// Alternative name ideas: IPSubnet, IPAddressSpace
public readonly struct IPNetwork : IEquatable<IPSubnet>, ISpanFormattable, ISpanParsable<IPSubnet>
{
public IPAddress BaseAddress { get; }
public byte MaskLength { get; }
public IPNetwork(IPAddress baseAddress, byte maskLength);
public bool Contains(IPAddress address);
// ISpanParsable
public static IPNetwork Parse(string s, IFormatProvider? provider = null);
public static bool TryParse(string s, IFormatProvider? provider, out IPNetwork result);
public static IPNetwork Parse(ReadOnlySpan<char> s, IFormatProvider? provider = null);
public static bool TryParse(ReadOnlySpan<char> s, IFormatProvider? provider, out IPNetwork result);
// Parsing - Convenience methods
public static bool TryParse(string s, out IPNetwork result);
public static bool TryParse(ReadOnlySpan<char> s, out IPNetwork result);
// ISpanFormattable
public string ToString(string? format, IFormatProvider? provider = null);
public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider? provider = null);
// Equality
public bool Equals(IPNetwork value);
public static bool operator ==(IPNetwork left, IPNetwork right);
public static bool operator !=(IPNetwork left, IPNetwork right);
}
API Usage
We're using this for parsing and logging, so the parsing and tostring functionality are particularly interesting.
Alternative Designs
This type could potentially implement ISpanFormattable<T>
and ISpanParsable<T>
, but those interfaces require an IFormatProvider instance which isn't relevant in this context. Still, those interfaces might provide better interop elsewhere in the framework. Note that IPAddress
doesn't implement these interfaces either.
Risks
No response