C# 获取外网IP

 1 /// <summary>
 2         /// 取得外网 IP Address
 3         /// </summary>
 4         /// <returns></returns>
 5         private string GetExtranetIPAddress()
 6         {
 7             HttpWebRequest request = HttpWebRequest.Create("http://www.whatismyip.com.tw") as HttpWebRequest;
 8             request.Method = "GET";
 9             request.ContentType = "application/x-www-form-urlencoded";
10             request.UserAgent = "Mozilla/5.0";
11             string ip = string.Empty;
12             WebResponse response = request.GetResponse();
13             using (StreamReader reader = new StreamReader(response.GetResponseStream()))
14             {
15                 string result = reader.ReadToEnd();
16                 string pattern = @"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}";
17                 ip = Regex.Match(result, pattern).ToString();
18             }
19             return ip; // result: 210.125.21.xxx
20         }
View Code
 /// <summary>
        /// 获取外网IP地址
        /// </summary>
        public static string GetIPAddress()
        {
            string sValue = String.Empty;
            string strUrl = "http://iframe.ip138.com/ic.asp"; //获得IP的网址  
            Uri uri = new Uri(strUrl);
            WebRequest wr = WebRequest.Create(uri);
            Stream s = wr.GetResponse().GetResponseStream();
            StreamReader sr = new StreamReader(s, Encoding.Default);
            string all = sr.ReadToEnd(); //读取网站的数据  
            Match match;
            string pattern = "(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)";
            match = Regex.Match(all, pattern, RegexOptions.IgnoreCase);
            return match.ToString();
        }

 

posted @ 2013-11-05 15:23  天王星天  阅读(256)  评论(0)    收藏  举报