0

我需要将 IP 范围转换为其子网的起始 IP。

例如,输入:

1.1.1.0 - 1.1.1.255
(255.255.255.0)

输出:

1.1.1.0/24

谢谢,

4

1 回答 1

0

使用按位运算符很容易:

byte[] ip1 = {1, 1, 1, 0};
byte[] ip2 = {1, 1, 1, 255};
byte[] omask = 
{
    (byte)(ip1[0] ^ ip2[0]), 
    (byte)(ip1[1] ^ ip2[1]), 
    (byte)(ip1[2] ^ ip2[2]),
    (byte)(ip1[3] ^ ip2[3])
};
string mask = Convert.ToString(omask[0], 2) + Convert.ToString(omask[1], 2)
              + Convert.ToString(omask[2], 2) + Convert.ToString(omask[3], 2);
// count the number of 1's in the mask. Substract to 32:
// NOTE: the mask doesn't have all the zeroes on the left, but it doesn't matter
int bitsInMask = 32 - (mask.Length - mask.IndexOf("1")); // this is the /n part
byte[] address = 
{
    (byte)(ip1[0] & ip2[0]), 
    (byte)(ip1[1] & ip2[1]), 
    (byte)(ip1[2] & ip2[2]),
    (byte)(ip1[3] & ip2[3])
};
string cidr = address[0] + "." + address[1] + "." 
    + address[2] + "." + address[3] + "/" + bitsInMask;

cidr 为您提供网络排名。

于 2012-05-10T23:56:35.760 回答