//webconfig
<add key="IPRange" value="0.0.0.0-0.0.0.0"/>
<!--<add key="IPRange" value="startIP-endIP"/>-->
//定义允许的IP端,格式如 :static string[] IPRange= { "0.0.0.0-0.0.0.0", "0.0.0.0-0.0.0.0", "192.168.0.0-192.168.255.255" };
//主函数,调用判断接口
static void Main()
{
//判断192.168.100.0这个ip是否在指定的IP范围段内
string ip = GetIP();
string IPRange = System.Configuration.ConfigurationManager.AppSettings["IPRange"].ToString(); if (IPRange != "startIP-endIP") { bool power = false; if (IPRange.IndexOf(',') > 0) { string[] AllowIPRanges = IPRange.Split(','); power = TheIpIsRange(ip, AllowIPRanges); } else { power = TheIpIsRange(ip, IPRange); } if (power == false) Response.Redirect("error.htm"); }
}
/// <summary>
/// 获取当前请求的IP地址
/// </summary>
/// <returns></returns>
public static string GetIP()
{
//获取IP地址
HttpRequest request = HttpContext.Current.Request;
string ipAddress = string.Empty;
if (request.ServerVariables["HTTP_X_FORWARDED_FOR"] == null || request.ServerVariables["HTTP_X_FORWARDED_FOR"] == "")
{
ipAddress = request.ServerVariables["REMOTE_ADDR"];
}
else if (request.ServerVariables["HTTP_X_FORWARDED_FOR"].IndexOf(",") >= 0)
{
int index = request.ServerVariables["HTTP_X_FORWARDED_FOR"].IndexOf(",");
ipAddress = request.ServerVariables["HTTP_X_FORWARDED_FOR"].Substring(0, index - 1);
}
else if (request.ServerVariables["HTTP_X_FORWARDED_FOR"].IndexOf(";") >= 0)
{
int index = request.ServerVariables["HTTP_X_FORWARDED_FOR"].IndexOf(";");
ipAddress = request.ServerVariables["HTTP_X_FORWARDED_FOR"].Substring(0, index - 1);
}
else
{
ipAddress = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
}
if (ipAddress == "127.0.0.1")
{
ipAddress = GetLocalhostIPAddress();
}
return ipAddress;
}
/// <summary>
/// 获取本机IP
/// </summary>
/// <returns></returns>
private static string GetLocalhostIPAddress()
{
string hostName = System.Net.Dns.GetHostName();
System.Net.IPHostEntry hostInfo = System.Net.Dns.GetHostByName(hostName);
System.Net.IPAddress[] IpAddr = hostInfo.AddressList;
string localIP = string.Empty;
for (int i = 0; i < IpAddr.Length; i++)
{
localIP += IpAddr[i].ToString();
}
return localIP;
}
//接口函数 参数分别是你要判断的IP 和 你允许的IP范围
//(已经重载)
//(允许同时指定多个数组)
public static bool TheIpIsRange(string ip, params string[] ranges)
{
bool tmpRes = false;
foreach (var item in ranges)
{
if (TheIpIsRange(ip, item))
{
tmpRes = true; break;
}
}
return tmpRes;
}
/// <summary>
/// 判断指定的IP是否在指定的IP范围内 这里只能指定一个范围
/// </summary>
/// <param name="ip"></param>
/// <param name="ranges"></param>
/// <returns></returns>
public static bool TheIpIsRange(string ip, string ranges)
{
bool result = false;
int count;
string start_ip, end_ip;
//检测指定的IP范围 是否合法
TryParseRanges(ranges, out count, out start_ip, out end_ip);//检测ip范围格式是否有效
if (ip == "::1") ip = "127.0.0.1";
try
{
IPAddress.Parse(ip);//判断指定要判断的IP是否合法
}
catch (Exception)
{
throw new ApplicationException("要检测的IP地址无效");
}
if (count == 1 && ip == start_ip) result = true;//如果指定的IP范围就是一个IP,那么直接匹配看是否相等
else if (count == 2)//如果指定IP范围 是一个起始IP范围区间
{
byte[] start_ip_array = Get4Byte(start_ip);//将点分十进制 转换成 4个元素的字节数组
byte[] end_ip_array = Get4Byte(end_ip);
byte[] ip_array = Get4Byte(ip);
bool tmpRes = true;
for (int i = 0; i < 4; i++)
{
//从左到右 依次比较 对应位置的 值的大小 ,一旦检测到不在对应的范围 那么说明IP不在指定的范围内 并将终止循环
if (ip_array[i] > end_ip_array[i] || ip_array[i] < start_ip_array[i])
{
tmpRes = false; break;
}
}
result = tmpRes;
}
return result;
}
//尝试解析IP范围 并获取闭区间的 起始IP (包含)
private static void TryParseRanges(string ranges, out int count, out string start_ip, out string end_ip)
{
string[] _r = ranges.Split('-');
if (!(_r.Count() == 2 || _r.Count() == 1))
throw new ApplicationException("IP范围指定格式不正确,可以指定一个IP,如果是一个范围请用“-”分隔");
count = _r.Count();
start_ip = _r[0];
end_ip = "";
try
{
IPAddress.Parse(_r[0]);
}
catch (Exception)
{
throw new ApplicationException("IP地址无效");
}
if (_r.Count() == 2)
{
end_ip = _r[1];
try
{
IPAddress.Parse(_r[1]);
}
catch (Exception)
{
throw new ApplicationException("IP地址无效");
}
}
}
/// <summary>
/// 将IP四组值 转换成byte型
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
static byte[] Get4Byte(string ip)
{
string[] _i = ip.Split('.');
List<byte> res = new List<byte>();
foreach (var item in _i)
{
res.Add(Convert.ToByte(item));
}
return res.ToArray();
}