我希望我的网站应用程序只能从精确的IP地址范围访问。
如果客户端IP不在WEB.Config应用程序中保存的范围内,应用程序必须拒绝我的页面访问。
我希望我的网站应用程序只能从精确的IP地址范围访问。
如果客户端IP不在WEB.Config应用程序中保存的范围内,应用程序必须拒绝我的页面访问。
那么我们如何将这些IP范围添加到Web.config中呢?
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="IP" value="31.171.126.0/255,31.171.127.0/255"/>
</appSettings>
<system.web>
<customErrors mode="Off"/>
<compilation debug="true"/>
<authentication mode="None"/>
</system.web>
</configuration>
Code behind的工作原理:
protected void Page_Load(object sender, EventArgs e)
{
var allowed = false;
//Get IP ranges from Web.config
// AS you see in web.config different IP ranges is seperated by comma
var ip = ConfigurationManager.AppSettings["IP"];
// Get Client Ip
lblIp.Text = GetIpAddress().Split(':')[0];
var clientIp = GetIpAddress();
var list = ip.Split(',');
//Do search inside IP ranges and see if client IP is inside IP ranges which is allowed to open web app.
foreach (var item in list)
{
var range = Convert.ToInt32(item.Split('/')[1].ToString(CultureInfo.InvariantCulture));
for (var i=0; i <= range; i++)
{
var submaskip = item.Split('/')[0].Split('.')[0] + "." + item.Split('/')[0].Split('.')[1] + "." +
item.Split('/')[0].Split('.')[2] + "." + i;
if (clientIp == submaskip)
{
allowed = true;
}
}
}
if (allowed == false)
{
Response.Redirect("Denied.aspx");
}
}
// Get Client IP
protected string GetIpAddress()
{
var context = System.Web.HttpContext.Current;
var ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ipAddress)) return context.Request.ServerVariables["REMOTE_ADDR"];
var addresses = ipAddress.Split(',');
return addresses.Length != 0 ? addresses[0] : context.Request.ServerVariables["REMOTE_ADDR"];
}