csharp-ip-address-range

How to Parse IP Ranges with C# IpaddressRange

  • 1 min

IpAddressRange for .NET is an Open Source .NET library that simplifies working with IP address ranges.

It provides functions to parse IPs from string format, supporting a wide variety of formats.

Once an IP range object is defined, it provides comparison and range membership verification operations.

The library is compatible with both IPv4 and IPv6 IP address versions and supports three different range formats: CIDR, subnet mask, and IP address range.

How to Use IpAddressRange

We can easily add the library to a .NET project via the corresponding Nuget package.

Install-Package IPAddressRange

Here are some examples of how to use IpAddressRange, extracted from the library’s documentation.

using NetTools;
...
// rangeA.Begin is "192.168.0.0", and rangeA.End is "192.168.0.255".
var rangeA = IPAddressRange.Parse("192.168.0.0/255.255.255.0");
rangeA.Contains(IPAddress.Parse("192.168.0.34")); // is True.
rangeA.Contains(IPAddress.Parse("192.168.10.1")); // is False.
rangeA.ToCidrString(); // is 192.168.0.0/24

// rangeB.Begin is "192.168.0.10", and rangeB.End is "192.168.10.20".
var rangeB1 = IPAddressRange.Parse("192.168.0.10 - 192.168.10.20");
rangeB1.Contains(IPAddress.Parse("192.168.3.45")); // is True.
rangeB1.Contains(IPAddress.Parse("192.168.0.9")); // is False.

// IEnumerable<IPAddress> support, it's lazy evaluation.
foreach (var ip in IPAddressRange.Parse("192.168.0.1/23"))
{
    Console.WriteLine(ip);
}
Copied!