2012-05-10 16 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-netmask-is-given – 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。

関連する問題