In fact, the use of Baidu's IP library function interface, and then deal with the line, as follows:
Preparatory work:
1. Register as an open developer, create an app to get the AK key for Baidu API call, Baidu Development Center address:http://developer.baidu.com/
2.API Address: http://developer.baidu.com/map/index.php?title=webapi/ip-api#.E4.BD.BF.E7.94.A8.E6.96.B9.E6.B3.95
3. To prepare for development, proceed as follows:
(1) Get client IP
/// <summary>Get client IP address (ignore proxy)</summary> /// <returns>returns the loopback address if it fails</returns> Public Static stringgethostaddress () {stringUserHostAddress =HttpContext.Current.Request.UserHostAddress; if(string. IsNullOrEmpty (userhostaddress)) {userhostaddress= httpcontext.current.request.servervariables["REMOTE_ADDR"]; } //finally determine if the acquisition was successful and check the format of the IP address (it is important to check its format) if(!string. IsNullOrEmpty (userhostaddress) &&IsIP (userhostaddress)) { returnuserhostaddress; } return "127.0.0.1"; } /// <summary> ///Check IP address format/// </summary> /// <param name= "IP" ></param> /// <returns></returns> Public Static BOOLIsIP (stringIP) { returnSystem.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) Get the coding service address
Private Const stringThe_key ="***************";//your AK key. /// <summary>return UTF-8 encoded service address</summary> /// <returns>Service Address</returns> Public stringGetposturl (stringTheip) { stringPostURL ="http://api.map.baidu.com/location/ip?ak="+ The_key +"&ip="+ Theip +"&coor=bd09ll"; returnPostURL; }
(3) Get the address resolution result through the service address
/// <summary>return results (result of address resolution)</summary> Public Static stringGetinfobyurl (stringURL) { //You only need to pass the URL of the spell to the function when you call it. The return value can be judged stringstrret =NULL; if(url = =NULL|| Url. Trim (). ToString () = ="") { returnstrret; } stringTargetUrl =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= -* -* +; WebResponse HS=HR. GetResponse (); Stream SR=HS. GetResponseStream (); StreamReader ser=NewStreamReader (SR, Encoding.default); Strret=ser. ReadToEnd (); } Catch(Exception ex) {strret=NULL; } returnstrret; }
(4) The last simple call to the above method, and then convert the following string to the literal character
string Theip = ymethod.gethostaddress (); string msg = Ymethod.getinfobyurl (Getposturl (THEIP)); = System.Text.RegularExpressions.Regex.Unescape (msg); Response.Write (msg);
Test address: http://ycdoit.com/test/getiptoad.aspx
"ASP." returns corresponding location information based on IP