Loading

.NET记录-获取外网IP以及判断该IP是属于网通还是电信

在工作时,需要获取服务器公网IP(外网IP),并且判断该IP地址是属于网通还是电信。花时间整理一下,自己实现的代码,以及后续遇到的问题。

 1         /// <summary>
 2         /// 获取外网IP
 3         /// </summary>
 4         /// <returns>IP</returns>
 5         public static string GetOuterIP()
 6         {
 7             string IP = string.Empty;
 8             Uri uri = new Uri("http://www.ip138.com/ips138.asp");
 9             System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
10             req.Method = "get";
11             using (System.IO.Stream s = req.GetResponse().GetResponseStream())
12             {
13                 using (System.IO.StreamReader reader = new System.IO.StreamReader(s))
14                 {
15                     char[] ch = { '[', ']' };
16                     string str = reader.ReadToEnd();
17                     System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(str, @"\[(?<IP>[0-9\.]*)\]");
18                     IP= m.Value.Trim(ch);
19 
20                 }
21             }
22             return IP;
23         }

 

 1 /// <summary>
 2         /// 判断ip是电信还是网通,网通为0,电信为1
 3         /// </summary>
 4         /// <returns></returns>
 5         public static string GetLocation()
 6         {
 7             string location = "0";
 8             try
 9             {
10                 Uri uri = new Uri("http://www.ip138.com/ips138.asp");
11                 System.Net.HttpWebRequest req = System.Net.WebRequest.Create(uri) as System.Net.HttpWebRequest;
12                 if (req != null)
13                 {
14                     req.Method = "get";
15                     using (System.IO.Stream s = req.GetResponse().GetResponseStream())
16                     {
17                         using (System.IO.StreamReader reader = new System.IO.StreamReader(s, Encoding.GetEncoding("gb2312")))
18                         {
19                             string str = reader.ReadToEnd();
20                             if (str.Contains("电信"))
21                             {
22                                 location = "1";
23                             }
24                         }
25                     }
26                 }
27             }
28             catch
29             {
30                 location = "0";
31             }
32             return location;
33         }

 

因为加班太多,工作任务紧张,所以欠考虑,没有在获取数据之后自己存储,后面遇到502,导致网站异常。

  • 因为获取的外网IP和方位都依赖于外部网站,所以需要考虑,当访问量过大时,ip138为防止服务器瘫痪,将会禁止访问。
  • 建议获取外网IP和方位之后,将外网IP和方位存储,可借助数据库、Redis、MemCache,甚至在服务器写入txt文件,来存储获取的外网IP和方位。
posted @ 2016-05-16 15:32  repeatedly  阅读(578)  评论(1编辑  收藏  举报