将ip范围转换为带子网的ip

时间:2012-05-10 22:37:58

标签: c# network-programming subnet

我需要将IP范围转换为使用其子网启动IP。

例如,输入:

1.1.1.0 - 1.1.1.255
(255.255.255.0)

输出:

1.1.1.0/24

感谢,

1 个答案:

答案 0 :(得分: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为您提供网络排名。

相关问题