Ejemplo n.º 1
0
        /// <summary>
        /// 由IP地址查找对应的位置信息的字符串
        /// </summary>
        public string Query2(string ip)
        {
            IpLocation result = Query(ip);

            return((result.Country + result.Local).Replace("CZ88.NET", ""));
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 由IP地址查找对应的位置信息
        /// </summary>
        /// <param name="ip"> 要查找的IP地址 </param>
        /// <returns> </returns>
        /// <exception cref="ArgumentException"></exception>
        public IpLocation Query(string ip)
        {
            if (ip == "::1")
            {
                ip = "127.0.0.1";
            }
            if (!Regex.Match(ip).Success)
            {
                throw new ArgumentException("IP格式错误");
            }
            IpLocation ipLocation = new IpLocation {
                Ip = ip
            };
            long intIp = IpToInt(ip);

            if ((intIp >= IpToInt("127.0.0.1") && (intIp <= IpToInt("127.255.255.255"))))
            {
                ipLocation.Country = "本机内部环回地址";
                ipLocation.Local   = "";
            }
            else
            {
                if ((((intIp >= IpToInt("0.0.0.0")) && (intIp <= IpToInt("2.255.255.255"))) ||
                     ((intIp >= IpToInt("64.0.0.0")) && (intIp <= IpToInt("126.255.255.255")))) ||
                    ((intIp >= IpToInt("58.0.0.0")) && (intIp <= IpToInt("60.255.255.255"))))
                {
                    ipLocation.Country = "网络保留地址";
                    ipLocation.Local   = "";
                }
            }
            long right = Count;
            long left  = 0L;
            long startIp;
            long endIpOff;
            int  countryFlag;

            while (left < (right - 1L))
            {
                long middle = (right + left) / 2L;
                startIp = GetStartIp(middle, out endIpOff);
                if (intIp == startIp)
                {
                    left = middle;
                    break;
                }
                if (intIp > startIp)
                {
                    left = middle;
                }
                else
                {
                    right = middle;
                }
            }
            startIp = GetStartIp(left, out endIpOff);
            long endIp = GetEndIp(endIpOff, out countryFlag);

            if ((startIp <= intIp) && (endIp >= intIp))
            {
                string local;
                ipLocation.Country = GetCountry(endIpOff, countryFlag, out local);
                ipLocation.Local   = local.Replace("(我们一定要解放台湾!!!)", "");
            }
            else
            {
                ipLocation.Country = "未知";
                ipLocation.Local   = "";
            }
            return(ipLocation);
        }