获得客户端外网IP地址

#region 获得客户端外网IP地址
        
/// <summary>
        
/// 获得客户端外网IP地址
        
/// </summary>
        
/// <returns>IP地址</returns>
        public static string GetClientInternetIP()
        {
            
string ipAddress = "";
            
using (WebClient webClient = new WebClient())
            {
                
try
                {
                    ipAddress 
= webClient.DownloadString("http://www.ip138.com/ip2city.asp");//站获得IP的网页
                    Regex myRegex = new Regex(@"(\d{1,3}(\.\d{1,3}){3})", RegexOptions.IgnoreCase);
                    ipAddress 
= myRegex.Match(ipAddress).Groups[1].Value;
                    
//判断IP是否合法
                    if (!System.Text.RegularExpressions.Regex.IsMatch(ipAddress, "[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}"))
                    {
                        ipAddress 
= webClient.DownloadString("http://www.zu14.cn/ip/");//站获得IP的网页
                    }
                }
                
catch (Exception)
                {
                }
                
            }
            
return ipAddress;
        }
        
#endregion

 string _LANip = "";//本地IP

            
            System.Net.IPHostEntry ipHost 
= System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()); ;
            System.Net.IPAddress ipaddress 
= ipHost.AddressList[0];
            _LANip 
= ipaddress.ToString();

 

 

posted @ 2010-09-02 10:18  21天后  阅读(453)  评论(1编辑  收藏  举报
21