获取本地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地址。
3 回答
拉丁的传说
TA贡献1789条经验 获得超8个赞
private IPAddress LocalIPAddress(){ if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()) { return null; } IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName()); return host .AddressList .FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork);}
:)
- 3 回答
- 0 关注
- 518 浏览
添加回答
举报
0/150
提交
取消