Language: EN

csharp-ip-address-range

How to Parse IP Ranges with C# IpaddressRange

IpAddressRange in .NET is an open-source library that makes working with IP address ranges easy.

It provides functions for parsing IPs in text string format, supporting a wide variety of formats.

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

The library is compatible with both IPv4 and IPv6 versions of IP addresses 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 through the corresponding Nuget package.

Install-Package IPAddressRange

Here are some examples of how to use IpAddressRange taken from the library 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);
}

IpAddressRange is open-source, and all the code and documentation is available in the project repository at https://github.com/jsakamoto/ipaddressrange/