其實就是使用了百度的IP庫的功能接口,而後處理下就好了,效果圖以下:php
準備工做:web
1.註冊成爲開度開發者,建立應用得到百度API調用的AK祕鑰,百度開發中心地址:http://developer.baidu.com/api
2.API 地址: http://developer.baidu.com/map/index.php?title=webapi/ip-api#.E4.BD.BF.E7.94.A8.E6.96.B9.E6.B3.95函數
3.準備開發咯,步驟以下:post
(1)獲取客戶端IP編碼
/// <summary>獲取客戶端IP地址(無視代理)</summary> /// <returns>若失敗則返回回送地址</returns> public static string GetHostAddress() { string userHostAddress = HttpContext.Current.Request.UserHostAddress; if (string.IsNullOrEmpty(userHostAddress)) { userHostAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; } //最後判斷獲取是否成功,並檢查IP地址的格式(檢查其格式很是重要) if (!string.IsNullOrEmpty(userHostAddress) && IsIP(userHostAddress)) { return userHostAddress; } return "127.0.0.1"; } /// <summary> /// 檢查IP地址格式 /// </summary> /// <param name="ip"></param> /// <returns></returns> public static bool IsIP(string ip) { return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
(2)獲取編碼服務地址url
private const string THE_KEY = "***************"; //你的AK密鑰 /// <summary>返回UTF-8編碼服務地址</summary> /// <returns>服務地址</returns> public string GetPostUrl(string theIP) { string postUrl = "http://api.map.baidu.com/location/ip?ak=" + THE_KEY + "&ip=" + theIP + "&coor=bd09ll"; return postUrl; }
(3)經過服務地址,獲得地址解析結果spa
/// <summary> 返回結果(地址解析的結果) </summary> public static string GetInfoByUrl(string url) { //調用時只須要把拼成的URL傳給該函數便可。判斷返回值便可 string strRet = null; if (url == null || url.Trim().ToString() == "") { return strRet; } string targeturl = url.Trim().ToString(); try { HttpWebRequest hr = (HttpWebRequest)WebRequest.Create(targeturl); hr.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"; hr.Method = "GET"; hr.Timeout = 30 * 60 * 1000; WebResponse hs = hr.GetResponse(); Stream sr = hs.GetResponseStream(); StreamReader ser = new StreamReader(sr, Encoding.Default); strRet = ser.ReadToEnd(); } catch (Exception ex) { strRet = null; } return strRet; }
(4)最後簡單的調用上面的方法,而後轉換下字符串中轉義字符代理
string theIP = YMethod.GetHostAddress(); string msg = YMethod.GetInfoByUrl(GetPostUrl(theIP)); msg = System.Text.RegularExpressions.Regex.Unescape(msg); Response.Write(msg);