文章内容

C# 根据IP获取对应城市地址

  • 2018-06-25 23:47:32
  • 110
  • 0
  • 0

淘宝接口:http://ip.taobao.com/service/getIpInfo.php?ip=x.x.x.x

获取访问者IP地址:

 /// <summary>
 /// 获取访问者IP
 /// </summary>
 public static string visitorip
 {
    get {
       string userIP;
       // HttpRequest Request = HttpContext.Current.Request;  
       HttpRequest Request = System.Web.HttpContext.Current.Request; // 如果使用代理,获取真实IP  
       if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != "")
          userIP = Request.ServerVariables["REMOTE_ADDR"];
       else
          userIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
          if (userIP == null || userIP == "")
             userIP = Request.UserHostAddress;
                return userIP;
        }
  }


根据访问者IP获取地址(JSON)

/// <summary>
/// 根据IP获取地址  淘宝
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
public static string GetIPAddress(string ip)
{
    string ipAddress = "";
    ip = ip.Replace("::1", "127.0.0.1");
    string url = "http://ip.taobao.com/service/getIpInfo.php?ip=" + ip;
    var request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "POST";
    request.ContentType = "application/json;charset=UTF-8";
    //接收数据
    var response = (HttpWebResponse)request.GetResponse();
    string json = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();
    //json = "[" + json + "]";
    TaoBaoIPAddress arr = JsonConvert.DeserializeObject<TaoBaoIPAddress>(json);
    if (arr != null)
    {
        if (arr.code == 0)
        {
            ipAddress = arr.data.country + arr.data.region + arr.data.city + " - " + arr.data.isp + arr.data.area;
        }
        else
        {
            ipAddress = "未知";
        }
    }
    else
    {
        ipAddress = "未知";
    }
    return ipAddress;
}
//淘宝返回JSON格式    
{
    "code": 0,
	"data": {
		"ip": "x.x.x.x",
		"country": "中国",
		"area": "",
		"region": "四川",
		"city": "绵阳",
		"county": "XX",
		"isp": "电信",
		"country_id": "CN",
		"area_id": "",
		"region_id": "510000",
		"city_id": "510700",
		"county_id": "xx",
		"isp_id": "100017"
	}
}


JSON类

public class TaoBaoIPAddress
{
   public int code { get; set; }
   public TaoBaoIPAddressInfo data { get; set; }
}
public class TaoBaoIPAddressInfo
{
   public string ip { get; set; }
   public string country { get; set; }
   public string area { get; set; }
   public string region { get; set; }
   public string city { get; set; }
   public string county { get; set; }
   public string isp { get; set; }
   public string country_id { get; set; }
   public string area_id { get; set; }
   public string region_id { get; set; }
   public string city_id { get; set; }
   public string county_id { get; set; }
   public string isp_id { get; set; }
}