接続元のIPアドレスが指定された範囲内かどうかを調べる


private bool IsInSubnet(string networkAddress, string netMask)
{
IPAddress clientIP = IPAddress.Parse(Request.UserHostAddress);
IPAddress networkIP = IPAddress.Parse(networkAddress);

byte[] clientIPInBytes = clientIP.GetAddressBytes();
string clientIPBits = null;
foreach(byte b in clientIPInBytes)
{
clientIPBits = clientIPBits + Convert.ToString(b,2).PadLeft(8,'0');
}

byte[] networkIPInBytes = networkIP.GetAddressBytes();
string networkIPBits = null;
foreach(byte b in networkIPInBytes)
{
networkIPBits = networkIPBits + Convert.ToString(b,2).PadLeft(8,'0');
}

int mask = int.Parse(netMask);
for(int i = 0; i < mask; i++)
{
if(clientIPBits[i] != networkIPBits[i])
{
return false;
}
}

return true;
}