【问题标题】:Converting an IP Address into CIDR将 IP 地址转换为 CIDR
【发布时间】:2017-08-23 09:51:14
【问题描述】:

我想设计一个代码,我可以在其中搜索输入的 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);

【问题讨论】:

    标签: c# ip subnet cidr


    【解决方案1】:

    我假设 CIDR 想要获取给定 IP 地址的分类网络掩码长度。 使用this wiki 作为参考,您可以将地址转换为位数组,然后检查第一个前导位。

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

    /// <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 计算。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-22
      • 2017-04-23
      • 2010-11-05
      • 1970-01-01
      • 1970-01-01
      • 2013-05-09
      相关资源
      最近更新 更多