一:Request.UserHostAddress.Trim() 取得客户端的IP地址。
二:多个ip段限制
#region
/// <summary>
/// 检测客户端ip是否在某一ip段内
/// </summary>
/// <param ClientIp> 客户端ip </param>
/// <returns> 1,通过;0;不通过 </returns>
public int IpExamination(string ClientIp)
{
string ksip = " ";//开始ip
string jsip = " ";//结束ip
long intksip;
long intjsip;
long intClientIp;
int returnvalue = 0;
string sql = "select top 1 ksip,jsip from tb_ipsd "; //数据库中的表
DataSet ds = db.dsSelect(sql);//
if (ds != null && ds.Tables[0].Rows.Count != 0)
{
ksip = ds.Tables[0].Rows[0][ "ksip "].ToString();
jsip = ds.Tables[0].Rows[0][ "jsip "].ToString();
}
intksip = IptoInt(ksip);
intjsip = IptoInt(jsip);
intClientIp = IptoInt(ClientIp);
//直接比较数值大小,判断是否在范围ip内
if (intClientIp > = intksip && intClientIp <= intjsip)
{
returnvalue = 1;
}
return returnvalue;
}
/// <summary>
/// 转换ip为数值类型
/// </summary>
/// <param ip> ip </param>
/// <returns> 数值ip </returns>
public long IptoInt(string ip)
{
long number;
string[] iparry = ip.Split( '. ');
number = long.Parse(iparry[0]) * 256 * 256 * 256 + long.Parse(iparry[1]) * 256 * 256 + long.Parse(iparry[2]) * 256 + long.Parse(iparry[3]);
return number;
}
/// <summary>
/// 获取客户端ip
/// </summary>
/// <param ip> ip </param>
/// <returns> ip值 </returns>
public string GetClientIP()
{
// string result = HttpContext.Current.Request.ServerVariables[ "HTTP_X_FORWARDED_FOR "];
// if (null == result || result == String.Empty)
// {
// result = HttpContext.Current.Request.ServerVariables[ "REMOTE_ADDR "];
// }
//if (null == result || result == String.Empty)
// {
// result = HttpContext.Current.Request.UserHostAddress;
// }
//string result = Page.Request.UserHostAddress;
string result = HttpContext.Current.Request.UserHostAddress;
return result;
}
#endregion
1. number = long.Parse(iparry[0]) * 256 * 256 * 256 + long.Parse(iparry[1]) * 256 * 256 + long.Parse(iparry[2]) * 256 + long.Parse(iparry[3]);
2. 192.168.1.1 --- 192.168.10.50 ===> 192.168.001.001 --- 192.168.010.050
192.168.3.123 ===> 192.168.003.123
(2只适用于在数据库中用sql语句,或者DataTable里面筛选)
"192.168.001.001 " < "192.168.003.123 " < "192.168.010.050 "
3. 192.168.1.1 --- 192.168.10.50 ===> 192168001001 --- 192168010050
192.168.3.123 ===> 192168003123
直接判断数字的大小。
二:单个IP限制
固定某个ip时,可以在WEB.CONFIG中
<!-- IP访问规则限制,修改value= " "中的数据 -->
<add key= "AllIP " value= "192.168.1.43,192.168.1.47,127.0.0.1 "/>
在页面中代码
string UserIP = System.Web.HttpContext.Current.Request.ServerVariables[ "REMOTE_ADDR "].ToString();
string[] ips = ConfigurationManager.AppSettings[ "AllIP "].ToString().Split( ", ".ToCharArray());
for (int i = 0; i < 3; i++)
{
if (ips[i] == UserIP)
{
System.Web.HttpContext.Current.Response.Redirect( "login.aspx ");
return;
}
else { System.Web.HttpContext.Current.Response.Write( "非法地址,禁止访问! "); }
}