【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 編輯過 |
關鍵字查詢
相關文章
正在查詢... |