判断ip 所在城市

来源:互联网 发布:linux sh命令参数 编辑:程序博客网 时间:2024/05/21 06:24

可先下载ip 数据库 sqlserver 2005 版  点击下载


public static string GetIpRealWorldAddress(string ipAddress)

        {
            if (!IpAddressAvailable(ipAddress))
            {
                return "ip地址有问题";
            }
            long value = GetIPCount(ipAddress);
            string Sql = string.Format("select * from ipLib where convert(float,ip_1)<= {0} and convert(float,ip_2) >= {0}", value);
            using (SqlConnection _SqlConnection = new SqlConnection("server=127.0.0.1;database=fy;uid=sa;pwd=**********"))
            {
                SqlCommand _SqlCommand = new SqlCommand(Sql, _SqlConnection);
                _SqlConnection.Open();
                SqlDataReader _SqlDataReader = _SqlCommand.ExecuteReader();
                if (_SqlDataReader.Read())
                {
                    string country = (string)_SqlDataReader["address"];
                    return country;
                }
                else
                {
                    return "没有找到匹配的记录!";
                }
            }
        }


        //取得ip的long值 3.254.255.255 = 3*256^3 + 254 *256^2 
        public static long GetIPCount(string ipAddress)
        {
            ipAddress = ipAddress.Trim();
            string[] ipSecs = ipAddress.Split('.');
            long value = 0;
            for (int i = 0; i < 4; i++)
            {
                int ipSecDec = int.Parse(ipSecs[i]);
                int power = 3 - i;
                long ipSecValue = (long)(ipSecDec * Math.Pow(256, power));
                value = value + ipSecValue;
            }
            value = value + 1;
            return value;
        }


        /// <summary>
        /// 判断ip地址是否有问题  1 地址段数, 地址段数里面是否是数字,数字是否在 0-255范围内
        /// 从以上三个方面监测
        /// </summary>
        /// <param name="ipAddress"></param>
        /// <returns></returns>
        private static bool IpAddressAvailable(string ipAddress)
        {
            ipAddress = ipAddress.Trim();
            string[] ipSecs = ipAddress.Split('.');
            if (ipSecs.Length != 4) return false;


            //如果每个段都可以转为int则返回真
            for (int i = 0; i < ipSecs.Length; i++)
            {
                try
                {
                    int ipSecDec = int.Parse(ipSecs[i]);
                    if (ipSecDec < 0 || ipSecDec > 255)
                    {
                        return false;
                    }
                }
                catch
                {
                    return false;
                }
            }
            return true;
        }