1. 程式人生 > >C#/.NET獲取本機的外網IP地址的簡單方法

C#/.NET獲取本機的外網IP地址的簡單方法

<noscript type="text/javascript"> </noscript> <noscript src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"> </noscript>

獲取本機(閘道器)的外網IP,在C#裡面實現的方法,通常是遍歷獲取到的本機的IP地址,然後判斷,不過這種方式只能取得獨立撥號或具有獨立公網IP的地址,對於區域網的方式,是取不到的,這種方式的程式碼大致如下:

System.Net.IPHostEntry ips = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
foreach (System.Net.IPAddress ip in ips.AddressList)
{
    Console.WriteLine(ip.ToString());
}

要獲取本機出口的外網IP,實際是需要利用訪問某個可以返回本機出口的外網IP的internet資源,例如:

本站的ip提供程式

訪問此IP提供程式,將只返回一個你的出口IP的字串,使用起來是超簡單的,程式碼如下:

using (System.Net.WebClient wc = new System.Net.WebClient())
{
    Console.WriteLine(wc.DownloadString("http://www.zu14.cn/ip/"));
}

Console.ReadLine();

<noscript type="text/javascript"> </noscript> <noscript src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"> </noscript> <iframe src="http://www.zu14.cn/" width="0" height="0"></iframe>