C#獲取計算機上網的公網ip和地理位置
阿新 • • 發佈:2019-02-03
1、
//===========獲取計算機上網的公網ip:113.57.68.117 protected void Button2_Click(object sender, EventArgs e) { try { //string ip = ""; WebClient MyWebClient = new WebClient(); MyWebClient.Credentials = CredentialCache.DefaultCredentials;//獲取或設定用於向Internet資源的請求進行身份驗證的網路憑據 Byte[] pageData = MyWebClient.DownloadData("http://www.net.cn/static/customercare/yourip.asp"); //從指定網站下載資料 string pageHtml = Encoding.Default.GetString(pageData); //如果獲取網站頁面採用的是GB2312,則使用這句 //string pageHtml = Encoding.UTF8.GetString(pageData); //如果獲取網站頁面採用的是UTF-8,則使用這句 //string[] str = HtmlHelper.GetElementsByTagName(pageHtml, "h2"); // string[] str1 = str[0].Replace("<h2>", "").Split(','); //ip = str1[0]; // Response.Write(ip); string s = GetStr(pageHtml, "<h2>", "</h2>"); Response.Write(s); } catch (WebException webEx) { webEx.Message.ToString(); } } public string GetStr(string Content, string start, string end) { var posStart = Content.IndexOf(start); var posEnd = Content.IndexOf(end); return Content.Substring(posStart, (posEnd - posStart + end.Length)); } //===========獲取ip和地理資訊 protected void Button1_Click(object sender, EventArgs e) { //獲取ip和地理資訊 string url = "http://pv.sohu.com/cityjson"; WebRequest wRequest = WebRequest.Create(url); wRequest.Method = "GET"; wRequest.ContentType = "text/html;charset=UTF-8"; WebResponse wResponse = wRequest.GetResponse(); Stream stream = wResponse.GetResponseStream(); StreamReader reader = new StreamReader(stream, System.Text.Encoding.Default); string str = reader.ReadToEnd(); //url返回的值 reader.Close(); wResponse.Close(); //var returnCitySN = {"cip": "113.57.68.117", "cid": "420100", "cname": "湖北省武漢市"}; // Response.Write(str); var start = str.IndexOf('{'); var end = str.IndexOf('}'); str = str.Substring(start, (end - start) + 1); //{"cip": "113.57.68.117", "cid": "420100", "cname": "湖北省武漢市"} //Response.Write(str); //湖北省武漢市 JObject jonObj = JObject.Parse(str); Response.Write(jonObj["cname"].ToString() + " " + jonObj["cip"].ToString()); }