c# - 将 IP 地址转换为 CIDR

标签 c# ip subnet cidr

我想设计一个代码,我可以在其中搜索输入的 IP 地址,并使用它给出 IP 地址的 CIDR 的输出。我需要输出是一个变量,因为我需要 CIDR 用于代码中的另一个步骤。

 static void Main(string[] args)
 {
            IPAddress addr = IPAddress.Parse("8.8.8.8");
            IPHostEntry entry = Dns.GetHostEntry(addr);
            Console.WriteLine("IP Address: " + addr);
            Console.WriteLine("Host Name: " + entry.HostName);

最佳答案

我假设您希望通过 CIDR 获得给定 IP 地址的有类网络掩码长度。 使用 this wiki作为引用,您可以将地址转换为位数组,然后检查第一个前导位。

这个有用的扩展类将您的 IP 地址转换为位(实际上是 bool 值):

/// <summary>
/// Converts an array of bytes to a BitArray instance, 
/// respecting the endian form of the operating system
/// </summary>
public static class BitArrayExtensions
{
    public static BitArray ToBitArray(this byte[] bytes)
    {
        bool[] allbits = new bool[bytes.Length * 8];
        for (int b = 0; b < bytes.Length; b++)
        {
            bool[] bits = new bool[8];
            new BitArray(new byte[] { bytes[b] }).CopyTo(bits, 0);
            if (BitConverter.IsLittleEndian)
                Array.Reverse(bits);

            bits.CopyTo(allbits, b * 8);
        }
        return new BitArray(allbits);
    }
}

有了这个类,就可以很容易地编写一个方法来找到 IP 地址的有类掩码长度:/8、/16 或/24

    /// <summary>
    /// Gets the length of the classful subnet mask of a given IPv4 address
    /// </summary>
    public int GetClassfulMaskbits(IPAddress address)
    {
        BitArray addressInBits = address.GetAddressBytes().ToBitArray();
        if (!addressInBits[0])  //leading bit = 0 => class A
            return 8; //default mask of class A = 255.0.0.0
        if(!addressInBits[1]) //leading bits = 10 => class B
            return 16; //default mask of class B = 255.255.0.0
        if (!addressInBits[2]) //leading bits = 110 => class C
            return 24; //default mask of class C = 255.255.255.0

        return 0; //class D or E has no classful subnet mask
    }

BitArray 扩展类也可用于其他 IP 计算。

关于c# - 将 IP 地址转换为 CIDR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43101464/

相关文章:

google-cloud-platform - 如何通过 CLI 获取 Google Cloud SQL 实例的 IP

sql - 创建一个包含来自子网列的 IP 地址的列

c# - Windows 窗体 - mac - xamarin

C# WPF 数据网格转换器

networking - Proxifier 是如何工作的?

amazon-web-services - Stubhub API 不接受来自 AWS 服务器的调用

networking - 为 Kubernetes 设置网络

amazon-web-services - RDS 子网组更改错误 "Can' 与 RDS 位于同一 VPC 上”

c# - PDFiumSharp PDF 转图像大小

c# - 数据绑定(bind) : 'System.String' does not contain a property with the name 'Text'