获取远程客户端IP地址
由于asp.net可能会使用反向代理,因此判断就多了几步,代码如下:
var ip = Request.HttpContext.Connection?.RemoteIpAddress?.ToString() ?? "0.0.0.0";
if (Request.Headers.ContainsKey("X-Real-IP"))
{
ip = Request.Headers["X-Real-IP"].ToString();
}
else if (Request.Headers.ContainsKey("X-Forwarded-For"))
{
ip = Request.Headers["X-Forwarded-For"].ToString();
}
else if (Request.Headers.ContainsKey("X-Original-For"))
{
var ipaddAdndPort = Request.Headers["X-Original-For"].ToArray()[0];
ip = ipaddAdndPort.Split(':')[0];
}
IP地址与数字之间的转换
public static class StringIpAddressExt
{
//把IP地址字符串转换成一个long
public static long IpToLong(this string ip)
{
var address = IPAddress.Parse(ip);
var a1 = IPAddress.HostToNetworkOrder((int)address.Address);
return (long)(uint)a1;
}
//把long转换成一个IP地址字符串
public static string LongToIp(this long lon)
{
var ipLong = IPAddress.NetworkToHostOrder((int)lon) & 0x00000000FFFFFFFF;
return new IPAddress(ipLong).ToString();
}
}
判断客户端IP地址是否在某一个范围内
string ip="192.168.240.123";
string ipStart="192.168.240.0";
string ipEnd="192.168.240.255";
var ipLong=ip.IpToLong();
var ipStartLong=ipStart.IpToLong();
var ipEndLong=ipEnd.IpToLong();
if(ipLong >= ipStartLong && ipLong <=ipEndLong)
{
//ip在范围内
}
//把long转换成Ip地址字符串
var ipAddress=ipLong.LongToIp();
IP地址范围列表
private List<Tuple<long, long>> FillIpRange(string ipConfigs)
{
var ipTemp = new List<Tuple<long, long>>();
foreach (var item in configuration.GetSection(ipConfigs).GetChildren())
{
if (item.Value.Contains("-"))
{
// "202.115.128.1-202.115.128.2",
var ips = item.Value.Split('-');
ipTemp.Add(new Tuple<long, long>(ips[0].IpToLong(), ips[1].IpToLong()));
continue;
}
if (item.Value.Contains("/"))
{
// "192.168.240.0/20",
// "202.115.128.0/255.255.255.0",
var ips = item.Value.Split('/');
if (ips[1].Length <= 2)
{
// "192.168.240.0/20",
var ip0 = ips[0].IpToLong();
var mask = int.Parse(ips[1]);
var bits = 0xFFFFFFFF << (32 - mask);
var aa1 = (ip0 | ~bits);
ipTemp.Add(new Tuple<long, long>(ip0 & bits, ip0 | ~bits));
}
else
{
// "202.115.128.0/255.255.255.0",
var ip0 = ips[0].IpToLong();
var mask = ips[1].IpToLong();
var ip1 = ip0 & mask;
var ip2 = ip0 | ~mask;
ipTemp.Add(new Tuple<long, long>(ip1, ip2));
}
continue;
}
//"202.115.128.2"
var ip01 = item.Value.IpToLong();
ipTemp.Add(new Tuple<long, long>(ip01, ip01));
}
return ipTemp;
}
|