猿问

获取本地IP地址

获取本地IP地址

在互联网上有几个地方告诉你如何获得一个IP地址。其中很多看起来就像这个例子:


String strHostName = string.Empty;

// Getting Ip address of local machine...

// First get the host name of local machine.

strHostName = Dns.GetHostName();

Console.WriteLine("Local Machine's Host Name: " + strHostName);

// Then using host name, get the IP address list..

IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);

IPAddress[] addr = ipEntry.AddressList;


for (int i = 0; i < addr.Length; i++)

{

    Console.WriteLine("IP Address {0}: {1} ", i, addr[i].ToString());

}

Console.ReadLine();

在这个例子中,我得到了几个IP地址,但我只感兴趣的是路由器分配给运行程序的计算机的IP地址:例如,如果某人希望访问我计算机中的共享文件夹,我会给他的IP地址。


如果我没有连接到一个网络,我是直接连接到互联网通过调制解调器,没有路由器,那么我想得到一个错误。我怎样才能知道我的计算机是否与C#连接到一个网络,以及它是否是为了获取LAN IP地址。


蝴蝶刀刀
浏览 519回答 3
3回答

拉丁的传说

重构Mrcheif的代码以利用Linq(即。.NET3.0+)..private&nbsp;IPAddress&nbsp;LocalIPAddress(){ &nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;null; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;IPHostEntry&nbsp;host&nbsp;=&nbsp;Dns.GetHostEntry(Dns.GetHostName()); &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;host&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.AddressList &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.FirstOrDefault(ip&nbsp;=>&nbsp;ip.AddressFamily&nbsp;==&nbsp;AddressFamily.InterNetwork);}:)
随时随地看视频慕课网APP
我要回答