通过拨号连接获取公网IP地址

很多时候,有需要用到本机公网IP地址,试了很多方法,一直不理想。

 

在这里有两种情况,一种是本机拨号的,一种是通过路由上网的。

 

一、如果是通过路由上网的,基本没有什么好办法,只有通过外网上一个页面返回自己的IP地址。

Http是我自己封装httpwebrequest使用的一个类,可以在网上搜到一大把资料。

 

代码
             // 获取公网IP
             private   string  GetInternetIP1()
            {
                
string  re  =   "" ;

                
try
                {
                    Http htp 
=   new  Http();

                    
string  html  =  htp.GetSyncHTML(htp.CreateWebRequest( " http://www.ip138.com/ip2city.asp " "" ));
                    
if  (html  !=   "" )
                    {
                        re 
=  RegexFunc.GetMatch(html,  " (?<=\\[)[\\s|\\S]*(?=\\]) " );

                    }
                }
                
catch  { }
                
return  re;
            }

 

 

二、如果是自己拨号的,有两种方法,但我推荐第二种

   第一种就是网上大部分推荐的,利用执行dos下的命令获取,ipconfig /all

  CmdPipe也是封装的一个执行dos命令的类,网上也能找到一大把(关键词,dos 管道)

  以下这种方法,在xp下通过,但并不适用所有操作系统,除非自己针对操作系统做不同的处理。

代码
                CmdPipe cp  =   new  CmdPipe();
                
string [] obj  =   new   string [] {  " ipconfig " " /all "  };
                
string  output  =  cp.RunCmd(obj);
                
string  A  =  RegexFunc.GetMatch(output,  " (?<=PPP adapter)[\\s|\\S]*?(?=Default Gateway) " );
                re 
=  RegexFunc.GetMatch(A,  " (?<=IP Address. . . . . . . . . . . . : )[\\s|\\S]*(?=Subnet Mask) " ).Trim( " \r\n\0 " .ToCharArray()).Trim();

 

  第二方法就是通过获取本地所有连接,如果连接的类型为Ppp 即为拨号连接,然后获取IP即可。目前已经在xp和win7上调试通过。

  

代码
using  System.Net.NetworkInformation;


                
string  re  =   "" ;
                NetworkInterface[] interfaces 
=  NetworkInterface.GetAllNetworkInterfaces();
                
foreach  (NetworkInterface ni  in  interfaces)
                {
                    
if  (ni.NetworkInterfaceType  ==  NetworkInterfaceType.Ppp)
                    {
                        
foreach  (UnicastIPAddressInformation ip  in  ni.GetIPProperties().UnicastAddresses)
                        {
                            
if  (ip.Address.AddressFamily  ==  System.Net.Sockets.AddressFamily.InterNetwork)
                            {
                                re
=  ip.Address.ToString();
                            }
                        }

                        
                    }
                }

 

 

你可能感兴趣的:(IP地址)