string ipLimit = "192.168.152.x,192.168.153.x,192.168.154.x,192.168.155.x,192.168.156.x,192.168.157.x,192.168.158.x,192.168.159.x,192.168.x.x";
string[] arrSeperators = { "," };
string[] ipList = ipLimit.Split(arrSeperators, StringSplitOptions.RemoveEmptyEntries);
if (!CheckIPLimit(ipList, GetRemoteIP()))
{
return“不可以访问”;
}
获得请求的IP地址函数GetRemoteIP():
private string GetRemoteIP()
{
string ip = "";
if (Context.Request.ServerVariables["HTTP_VIA"] != null) // 服务器, using proxy
{
//得到真实的客户端地址
ip = Context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString(); // Return real client IP.
}
else//如果没有使用代理服务器或者得不到客户端的ip not using proxy or can't get the Client IP
{
// 得到服务端的地址
ip = Context.Request.ServerVariables["REMOTE_ADDR"].ToString(); //While it can't get the Client IP, it will return proxy IP.
}
return ip;
}
}
下面的函数将string[] ipList与请求IP一一比较(分段比较):
private bool CheckIPLimit(string[] ipList, string remoteIP)
{
foreach (string ip in ipList)
{
if (CompareIP(ip, remoteIP))
{
return true;
}
}
return false;
}
private bool CompareIP(string oldIP, string newIP)
{
string[] arrSeperators = { "." };
string[] oldIPList = oldIP.Split(arrSeperators, StringSplitOptions.RemoveEmptyEntries);
string[] newIPList = newIP.Split(arrSeperators, StringSplitOptions.RemoveEmptyEntries);
if (oldIPList.Length != newIPList.Length)
{
return false;
}
for (int i = 0; i < oldIPList.Length; i++)
{
if (oldIPList[i] != checkedIP & oldIPList[i] != newIPList[i])//截取的ip是‘x’则是true
{
return false;
}
}
return true;
}