C#获取计算机上网的公网ip和地理位置

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("

", "").Split(','); //ip = str1[0]; // Response.Write(ip); string s = GetStr(pageHtml, "

", "

"); 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()); }


你可能感兴趣的:(c#)