在两者之间找到更大的子网(一个连续1' s的子网)

时间:2017-11-30 18:18:05

标签: c# c#-4.0

我有一个代码段,可以找到两个子网掩码之间的较大子网。代码片段使用左移操作符,恕我直言使代码无法读取(可能是因为我很少使用它,我相信现在很多开发人员都没有使用它)。

这是完成工作的代码。

        IPAddress subNet1 = IPAddress.Parse("255.255.255.0");
        IPAddress subNet2 = IPAddress.Parse("255.255.128.0");

        byte[] bytes;
        bytes = subNet1.GetAddressBytes();
        int tempSub1 = Convert.ToInt32((bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3]));

        bytes = subNet2.GetAddressBytes();
        int tempSub2 = Convert.ToInt32((bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3]));

        if(tempSub1 == tempSub2)
            Console.WriteLine("Pick Any Subnet");

        //Find Larger Subnet(Less number of contiguous 1's)
        if(tempSub1<tempSub2)
            Console.WriteLine("Subnet 1 is Larget Subnet");
        else
            Console.WriteLine("Subnet 2 is Larget Subnet");

我能想到的另一种方式是;为了便于阅读 将IP地址转换为二进制,将值存储在字符串中,然后比较1。

有哪些方法可以使代码更容易理解(对于那些不习惯转移运算符的人来说)?

2 个答案:

答案 0 :(得分:2)

这是将字节转换为整数的适当方法。但是,BitConverter可以隐藏肮脏的东西。

IPAddress subnet1 = IPAddress.Parse("255.255.255.0");
IPAddress subnet2 = IPAddress.Parse("255.255.128.0");

int subnet1Mask = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(subnet1.GetAddressBytes(), 0));
int subnet2Mask = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(subnet2.GetAddressBytes(), 0));

int cmp = -subnet1Mask.CompareTo(subnet2Mask);
if      (cmp < 0) { Console.WriteLine("Subnet 1 is smaller than Subnet 2."); }
else if (cmp > 0) { Console.WriteLine("Subnet 1 is larger than Subnet 2."); }
else              { Console.WriteLine("Subnet 1 and Subnet 2 have the same size."); }

也就是说,您可以简单地比较字节数组而不是转换为整数。

int compareSubnetSize(IPAddress subnet1, IPAddress subnet2)
{
    byte[] subnet1MaskBytes = subnet1.GetAddressBytes();
    byte[] subnet2MaskBytes = subnet2.GetAddressBytes();

    int cmp = 0;
    for (int i=0; i<4; ++i) {
        cmp = subnet1MaskBytes[i].CompareTo(subnet2MaskBytes[i]);
        if (cmp != 0)
            return -cmp;
    }

    return 0;
}

IPAddress subnet1 = IPAddress.Parse("255.255.255.0");
IPAddress subnet2 = IPAddress.Parse("255.255.128.0");

int cmp = compareSubnetSize(subnet1, subnet2);
if      (cmp < 0) { Console.WriteLine("Subnet 1 is smaller than Subnet 2."); }
else if (cmp > 0) { Console.WriteLine("Subnet 1 is larger than Subnet 2."); }
else              { Console.WriteLine("Subnet 1 and Subnet 2 have the same size."); }

答案 1 :(得分:0)

将IPv4地址作为字符串进行比较似乎比转换它们更容易。例如:

Regex.Replace("255.255.255.0", @"\d+", m => m.Value.PadLeft(3))       //  "255.255.255.  0"

string.Concat("255.255.255.0".Split('.').Select(s => s.PadLeft(4)))   // " 255 255 255   0"

BitConverter.ToString(IPAddress.Parse("255.255.255.0").GetAddressBytes())  // "FF-FF-FF-00"

string.Concat("255.255.255.0".Split('.').Select(s => $"{int.Parse(s):X2}")))  // "FFFFFF00"