简体   繁体   中英

Convert IP range to range of CIDR addresses c#

I have the following issue : i need to convert range of IP addresses into range of CIDR addresses without losses of addresses. For example, if i have the range 1.1.1.3 - 1.1.1.7 , i can convert it into

 1.1.1.1/29

using IPNetwork library, but if i will convert 1.1.1.1/29 to range again i get 1.1.1.1 - 1.1.1.6 . How could i divide ranges to get a few ranges in CIDR format without losses ? Will be good if you can show me any C# code to perform it.

using the IPNetwork2 nuget package, you could subnet into /32 and iterate over the result ips :

Example 8 of documentation :

IPNetwork wholeInternet = IPNetwork.Parse("1.1.1.1/29");
IPNetwork ips = IPNetwork.Subnet(wholeInternet, 32);

Console.WriteLine("All  :");

foreach (IPNetwork ip in ips)
{
    Console.WriteLine("{0}", ip);
}

Output

All  :
1.1.1.0
1.1.1.1
1.1.1.2
1.1.1.3
1.1.1.4
1.1.1.5
1.1.1.6
1.1.1.7

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM