How can I convert IP range to Cidr in C#?(如何在C#中将IP范围转换为CIDR?)
本文介绍了如何在C#中将IP范围转换为CIDR?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
将CIDR转换为IP范围的示例很多。但我想知道如何在C#中使用起始/结束IP地址生成一个/某些CIDR?例如: 我有起始IP地址(192.168.0.1)和结束IP地址(192.168.0.254)。因此使用这两个地址生成CIDR列表{192.168.0.0/31,192.168.0.2/32}。是否有C#代码示例?
推荐答案
很难确定此处具体询问的内容(您提供的CIDR列表似乎与给定的输入地址不一致),但是以下代码将允许您查找包含指定开始地址和结束地址的最小单个CIDR。
您需要先将起始IP地址和结束IP地址转换为32位整数(例如192.168.0.1变为0xc0a80001),然后应用以下算法:
var startAddr = 0xc0a80001; // 192.168.0.1
var endAddr = 0xc0a800fe; // 192.168.0.254
// Determine all bits that are different between the two IPs
var diffs = startAddr ^ endAddr;
// Now count the number of consecutive zero bits starting at the most significant
var bits = 32;
var mask = 0;
while (diffs != 0)
{
// We keep shifting diffs right until it's zero (i.e. we've shifted all the non-zero bits off)
diffs >>= 1;
// Every time we shift, that's one fewer consecutive zero bits in the prefix
bits--;
// Accumulate a mask which will have zeros in the consecutive zeros of the prefix and ones elsewhere
mask = (mask << 1) | 1;
}
// Construct the root of the range by inverting the mask and ANDing it with the start address
var root = startAddr & ~mask;
// Finally, output the range
Console.WriteLine("{0}.{1}.{2}.{3}/{4}", root >> 24, (root >> 16) & 0xff, (root >> 8) & 0xff, root & 0xff, bits);
在问题中的两个地址上运行它会得到:
192.168.0.0/24
这篇关于如何在C#中将IP范围转换为CIDR?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:如何在C#中将IP范围转换为CIDR?


基础教程推荐
猜你喜欢
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01