【C#】IP地址限制访问本服务器
当前位置:点晴教程→知识管理交流
→『 技术文档交流 』
string id = Request["id"];
if (id != null && id == "574")
{
string ip;
try
{
HttpRequest request = HttpContext.Current.Request;
if (request.ServerVariables["HTTP_VIA"] != null)
{
ip = request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString().Split(',')[0].Trim();
}
else
{
ip = request.UserHostAddress;
}
}
catch (Exception e)
{
throw e;
}
char[] dot = new char[] { '.' };
string[] ipArr = ip.Split(dot);
if (ipArr.Length == 3)
ip = ip + ".0";
ipArr = ip.Split(dot);
long ip_Int = 0;
long p1 = long.Parse(ipArr[0]) * 256 * 256 * 256;
long p2 = long.Parse(ipArr[1]) * 256 * 256;
long p3 = long.Parse(ipArr[2]) * 256;
long p4 = long.Parse(ipArr[3]);
ip_Int = p1 + p2 + p3 + p4;
bool ok = true;
////允许的IP地址范围:ipcheck
string[,] ipcheck = new string[,] { { "210.47.0.1", "210.47.0.255" }, { "192.168.0.1", "192.168.255.255" } };
for (int i = 0; i < ipcheck.GetLength(0); i++)
{
long ipcheck0 = 0;
ipArr = ipcheck[i, 0].Split(dot);
if (ipArr.Length == 3)
ipcheck[i, 0] = ipcheck[i, 0] + ".0";
ipArr = ipcheck[i, 0].Split(dot);
p1 = long.Parse(ipArr[0]) * 256 * 256 * 256;
p2 = long.Parse(ipArr[1]) * 256 * 256;
p3 = long.Parse(ipArr[2]) * 256;
p4 = long.Parse(ipArr[3]);
ipcheck0 = p1 + p2 + p3 + p4;
long ipcheck1 = 0;
ipArr = ipcheck[i, 1].Split(dot);
if (ipArr.Length == 3)
ipcheck[i, 0] = ipcheck[i, 1] + ".0";
ipArr = ipcheck[i, 1].Split(dot);
p1 = long.Parse(ipArr[0]) * 256 * 256 * 256;
p2 = long.Parse(ipArr[1]) * 256 * 256;
p3 = long.Parse(ipArr[2]) * 256;
p4 = long.Parse(ipArr[3]);
ipcheck1 = p1 + p2 + p3 + p4;
if (ip_Int < ipcheck0 || ip_Int > ipcheck1)
{
ok = false;
}
else
{
ok = true;
break;
}
}
if (!ok)
{
Response.Write("您的ip不允许访问此内容");
Response.End();
}
} 该文章在 2021/8/2 8:56:40 编辑过 |
关键字查询
相关文章
正在查询... |