微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

判断ip 所在城市

可先下载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;         }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐