2012-05-10 50 views
0

我需要將IP範圍轉換爲其子網的起始IP。將IP範圍轉換爲IP與子網

例如,輸入:

1.1.1.0 - 1.1.1.255 
(255.255.255.0) 

輸出:

1.1.1.0/24 

感謝,

+1

並非所有的範圍都會有適當的CIDR網絡掩碼;你打算如何處理這些? – sarnold

+0

來澄清:您期望爲1.1.1.3 - 1.1.1.5輸出什麼? – Vlad

+0

作爲參考,這與您所要求的相反:http://stackoverflow.com/questions/1470792/how-to-calculate-the-ip-range-when-the-ip-address-and -the-網絡掩碼,被賜予 – BeemerGuy

回答

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給你網絡r ANK。