C#联机获取公网IP

Posted on 2016-06-21 21:31  太息花色  阅读(1562)  评论(0)    收藏  举报

C#获取IP的方式有很多种,这里通过http://www.ipip.net/这个稳定的在线IP库的来获取公网IP。

 1 string tempip = "0.0.0.0";
 2 WebRequest wr = WebRequest.Create("http://www.ipip.net/");
 3 Stream s = wr.GetResponse().GetResponseStream();
 4 if (s != null)
 5 {
 6     StreamReader sr = new StreamReader(s, Encoding.UTF8);
 7     string all = sr.ReadToEnd();
 8     int start = all.IndexOf("您当前的IP:", StringComparison.Ordinal) + 7;
 9     int end = all.IndexOf("<", start, StringComparison.Ordinal);
10     tempip = all.Substring(start, end - start);
11     sr.Close();
12     s.Close();
13 }