文章内容
2017/9/1 9:10:43,作 者: 黄兵
获取ip归属地
最开始选择的是ip138的接口,后来出现请求过多会报网关超时等错误,然后尝试改成淘宝的接口,发现回传的归属地不准确于是最终选择了新浪的。
据观察,没有错误。
新浪语法 (以下是c#的语法,若是前台调用 可以将路径中的format改为=js)
////// 获取IP归属地 Edited by Sanne at 2016-03-24////// IP地址/// IP归属地public static string GetIPSource(string strIP){try{WebClient client = new WebClient();Stream myStream = client.OpenRead("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=xml&ip=" + strIP);if (myStream != null){StreamReader sr = new StreamReader(myStream, Encoding.GetEncoding("gb2312"));string strHtml = sr.ReadToEnd();myStream.Close();if (strHtml == "-3"){//这种情况一般是ip格式不对 可以写入日志观察下LogHelper.WriteProgramLog("GetIPSource():" + strIP + ",[" + strHtml + "]");return "归属地不详";}//返回的格式都是这样的‘1-1-1中国福建厦门’,但是不一定有6个长度,可能4个或者5个,所以解决办法替换掉-1,1和两端空格strHtml = strHtml.Replace("-1", "").Replace("1", "").Trim();return strHtml;}LogHelper.WriteProgramLog("GetIPSource():" + strIP + ",error:myStream is null!");return "归属地不详";}catch (Exception ex){LogHelper.WriteProgramLog("GetIPSource():" + strIP + ",Exception:" + ex.Message);return "归属地不详";}}// 新浪根据ip获取地址jQuery.getScript("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=" + ipInfo[0][0], function () {var country = "未知地点";var province = '';var city = '';if (window.remote_ip_info["ret"] == "1") {country = window.remote_ip_info["country"];//国家province = window.remote_ip_info["province"];//省city = window.remote_ip_info["city"];//市} });
评论列表