C# winfrom获取外网IP地址和物理地址

来源:互联网 发布:数据记录表 编辑:程序博客网 时间:2024/05/01 01:03

因项目需要,老大让做一个类似QQ那样能知道你的登陆地点的东西。

  这下慌啊,。后来找到一个网站 www.ip138.com

  进去看了一下惊喜啊羡慕,我要的东西里面都有。 可是,怎么样能将我想要的物理地址拿出来,放在我自己的项目中呢。

   下面的代码能解释一切

       try
            {
                string strUrl = "http://city.ip138.com/city.asp"; //获得IP的网址了
                Uri uri = new Uri(strUrl);
                System.Net.WebRequest wr = System.Net.WebRequest.Create(uri);
                System.IO.Stream s = wr.GetResponse().GetResponseStream();
                System.IO.StreamReader sr = new System.IO.StreamReader(s, System.Text.Encoding.Default);
                string all = sr.ReadToEnd(); //读取网站的数据

                int i = all.IndexOf("[") + 1;
                string tempip = all.Substring(i, 15);
                ip = tempip.Replace("]", "").Replace(" ", "");//找出公网IP
                int ii=all.LastIndexOf(":") + 1;
                Address = all.Substring(ii, all.LastIndexOf(" ") - all.LastIndexOf(":") - 1);//找出物理地址,如:江苏省苏州市
                label10.Text = "您当前所在的位置是:" + Address;
            }
            catch (Exception ex)
            {
            }

   问题一下子解决,唉,终于松了口气,那个叫心情舒畅啊

原创粉丝点击