C# 判断IP是否在中国

转载泥塘·物语 » 判断是否为中国IP
转载博主文章中有ip库文档,有需要的可以下载

	//获取配置文件中的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;
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值