Skip to content

[API Proposal]: Add a type to represent IP networks based on CIDR notation #79946

Description

@geeknoid

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.

namespaceSystem.Net;// Alternative name ideas: IPSubnet, IPAddressSpacepublicreadonlystructIPNetwork:IEquatable<IPSubnet>,ISpanFormattable,ISpanParsable<IPSubnet>{publicIPAddressBaseAddress{get;}publicbyteMaskLength{get;}publicIPNetwork(IPAddressbaseAddress,bytemaskLength);publicboolContains(IPAddressaddress);// ISpanParsablepublicstaticIPNetworkParse(strings,IFormatProvider?provider=null);publicstaticboolTryParse(strings,IFormatProvider?provider,outIPNetworkresult);publicstaticIPNetworkParse(ReadOnlySpan<char>s,IFormatProvider?provider=null);publicstaticboolTryParse(ReadOnlySpan<char>s,IFormatProvider?provider,outIPNetworkresult);// Parsing - Convenience methodspublicstaticboolTryParse(strings,outIPNetworkresult);publicstaticboolTryParse(ReadOnlySpan<char>s,outIPNetworkresult);// ISpanFormattablepublicstringToString(string?format,IFormatProvider?provider=null);publicboolTryFormat(Span<char>destination,outintcharsWritten,ReadOnlySpan<char>format=default,IFormatProvider?provider=null);// EqualitypublicboolEquals(IPNetworkvalue);publicstaticbooloperator==(IPNetworkleft,IPNetworkright);publicstaticbooloperator!=(IPNetworkleft,IPNetworkright);}

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

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions