如何在C#中将IP范围转换为CIDR?

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?

基础教程推荐