私はあなたが与えられたIPアドレスのクラスフルネットマスク長を取得したいCIDRで想定しています。 this wikiを参考にして、アドレスをビットの配列に変換し、最初の先頭ビットを確認することができます。
この便利な拡張機能クラスはビット(実際にはブール値)にあなたのIPアドレスを変換します
/// <summary>
/// Converts an array of bytes to a BitArray instance,
/// respecting the endian form of the operating system
/// </summary>
public static class BitArrayExtensions
{
public static BitArray ToBitArray(this byte[] bytes)
{
bool[] allbits = new bool[bytes.Length * 8];
for (int b = 0; b < bytes.Length; b++)
{
bool[] bits = new bool[8];
new BitArray(new byte[] { bytes[b] }).CopyTo(bits, 0);
if (BitConverter.IsLittleEndian)
Array.Reverse(bits);
bits.CopyTo(allbits, b * 8);
}
return new BitArray(allbits);
}
}
このクラスでは、あなたの処分で、それはIPのクラスフルマスク長を見つける方法を記述することは非常に簡単ですアドレス:/ 8、/ 16または/ 24
/// <summary>
/// Gets the length of the classful subnet mask of a given IPv4 address
/// </summary>
public int GetClassfulMaskbits(IPAddress address)
{
BitArray addressInBits = address.GetAddressBytes().ToBitArray();
if (!addressInBits[0]) //leading bit = 0 => class A
return 8; //default mask of class A = 255.0.0.0
if(!addressInBits[1]) //leading bits = 10 => class B
return 16; //default mask of class B = 255.255.0.0
if (!addressInBits[2]) //leading bits = 110 => class C
return 24; //default mask of class C = 255.255.255.0
return 0; //class D or E has no classful subnet mask
}
BitArray拡張クラスは、他のIP計算にも役立ちます。