gpt4 book ai didi

c# - 将 IP 地址转换为 CIDR

转载 作者:行者123 更新时间:2023-11-30 16:44:49 31 4
gpt4 key购买 nike

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

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com