发布:2022/12/22 11:04:49作者:管理员 来源:本站 浏览次数:640
//获取配置文件中的ip文档的存放路径
private static string FILE_NAME = ConfigurationManager.AppSettings["IpFilePath"];
// 只存放属于中国的ip段
private static Dictionary<int, List<int[]>> chinaIps = new Dictionary<int, List<int[]>>();
static LoginService()
{
Init();
}
/// <summary>
/// ip格式: add1.add2.add3.add4
/// key为 : add1*256+add2
/// value为int[2]: int[0]存的add3*256+add4的开始ip int[4]存的结束ip
/// 存放中国IP
/// </summary>
private static void Init()
{
try
{
// ip格式: add1.add2.add3.add4
// key为 : add1*256+add2
// value为int[2]: int[0]存的add3*256+add4的开始ip int[4]存的结束ip
Dictionary<int, List<int[]>> map = new Dictionary<int, List<int[]>>();
List<string> lines = File.ReadAllLines(FILE_NAME).ToList();
foreach (string line in lines)
{
if (line.StartsWith("apnic|CN|ipv4|"))
{
// 只处理属于中国的ipv4地址
string[] strs = line.Split(new string[] { "\\", "|" }, StringSplitOptions.RemoveEmptyEntries);
string ip = strs[3];
string[] add = ip.Split(new string[] { "\\", "." }, StringSplitOptions.RemoveEmptyEntries);
int count = int.Parse(strs[4]);
int startIp = int.Parse(add[0]) * 256 + int.Parse(add[1]);
while (count > 0)
{
if (count >= 65536)
{
// add1,add2 整段都是中国ip
chinaIps.Add(startIp, new List<int[]>());
count -= 65536;
startIp += 1;
}
else
{
int[] ipRange = new int[2];
ipRange[0] = int.Parse(add[2]) * 256 + int.Parse(add[3]);
ipRange[1] = ipRange[0] + count;
count -= count;
List<int[]> list = null;
if (map.ContainsKey(startIp))
{
list = map[startIp];
}
if (list == null)
{
list = new List<int[]>();
map.Add(startIp, list);
}
list.Add(ipRange);
}
}
}
}
chinaIps = chinaIps.Concat(map).ToDictionary(x => x.Key, x => x.Value); ;
}
catch (Exception e)
{
//Console.WriteLine(e.Message);
throw;
}
}
/// <summary>
/// 判断ip是否中国ip
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
public static bool IsChinaIp(string ip)
{
if (string.IsNullOrEmpty(ip))
{
return false;
}
string[] strs = ip.Split(new string[] { "\\", "." }, StringSplitOptions.RemoveEmptyEntries);
if (strs.Length != 4)
{
return false;
}
int key = int.Parse(strs[0]) * 256 + int.Parse(strs[1]);
List<int[]> list = null;
if (chinaIps.ContainsKey(key))
{
list = chinaIps[key];
}
if (list == null)
{
return false;
}
if (list.Count == 0)
{
// 整段都是中国ip
return true;
}
int ipValue = int.Parse(strs[2]) * 256 + int.Parse(strs[3]);
foreach (int[] ipRange in list)
{
if (ipValue >= ipRange[0] && ipValue <= ipRange[1])
{
return true;
}
}
return false;
}
© Copyright 2014 - 2024 柏港建站平台 ejk5.com. 渝ICP备16000791号-4