方法一:淘宝库查询
接口地址:http://ip.taobao.com/service/getIpInfo.php?ip=127.0.0.1
此方法查询速度慢,而且有查询次数限制,不推荐
方法二:ip-api查询
接口地址:http://ip-api.com/json/123.12.12.12?callback=?lang=zh-CN
查询注意事项
1、这种查询不支持本地查询,如你把ip地址写为127.0.0.1他是查不出来的
2、lang=zh-CN是国家代码,默认不写的话返回的是拼音
此方法返回结果全面,而且参数可配,推荐使用这种方法,api文档地址:https://ip-api.com/#docs/api
前端获取方法
资源地址在这里:https://download.csdn.net/download/duangufei/12524863
后端获取方法(C#)
//根据ip获取城市信息 public ResultModel<IPModel> GetIpDetail() {
//ip一定要是具体的ip地址 string hostAddress = GetHostAddress() == "127.0.0.1" ? "123.23.23.23" : GetHostAddress(); string url = "http://ip-api.com/json/"+ hostAddress + "?lang=zh-CN"; string cs = ""; WebClient client = new WebClient(); var buffer = client.DownloadData(url); ResultModel<IPModel> resultModel = new ResultModel<IPModel>(); try { string jsonText = Encoding.UTF8.GetString(buffer); JObject jo = JObject.Parse(jsonText); var ip = hostAddress; var name = jo["city"]; var regionName = jo["regionName"]; IPModel iPModel = new IPModel { region = regionName.ToString(), city = name.ToString(), }; resultModel = new ResultModel<IPModel> { ip = ip.ToString(), code = 0, data = iPModel }; } catch (System.Exception ) { } //int s = str.IndexOf('市'); return resultModel; }
//获取用户的ip地址 public static string GetHostAddress() { string userHostAddress = HttpContext.Current.Request.UserHostAddress; if (string.IsNullOrEmpty(userHostAddress)) { userHostAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; } if (!string.IsNullOrEmpty(userHostAddress) && IsIP(userHostAddress)) { return userHostAddress; } return "127.0.0.1"; }
//IP地址验证 public static bool IsIP(string ip) => Regex.IsMatch(ip, @"^((2[0-4]d|25[0-5]|[01]?dd?).){3}(2[0-4]d|25[0-5]|[01]?dd?)");