C# – 查找我的机器的本地IP地址而不是VM的

我的机器上安装了VirtualBox VM,因此有一个为其显示的以太网适配器。 我通过以下方式列举了我机器的IP地址列表:

public string GetLocalIpAddress() { try { string strHostName = Dns.GetHostName(); // Then using host name, get the IP address list.. IPHostEntry ipEntry = Dns.GetHostEntry(strHostName); foreach (IPAddress ip in ipEntry.AddressList) { if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { return string.Format("({0})", ip.ToString()); } } } catch(Exception e) { Global.ApplicationLog.AddApplicationLog(EnumAppEventTypes.SYSTEM_ERROR, e.ToString()); } return ""; } 

我的问题是虚拟机的以太网适配器也捕获了条件:

 if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) 

有没有办法挑选我的机器的本地IP地址并忽略我的虚拟机?

您可以按名称忽略以太网适配器。 由于VM以太网适配器由有效的NIC驱动程序表示,从操作系统的角度来看,它完全等同于机器的物理网卡。

我正在改进Andrej Arh的答案,因为GatewayAddresses报告的IP地址也可以是“0.0.0.0”而不是null:

  public static string GetPhysicalIPAdress() { foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces()) { var addr = ni.GetIPProperties().GatewayAddresses.FirstOrDefault(); if (addr != null && !addr.Address.ToString().Equals("0.0.0.0")) { if (ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet) { foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses) { if (ip.Address.AddressFamily == AddressFamily.InterNetwork) { return ip.Address.ToString(); } } } } } return String.Empty; } 

有一个选择。 VM IP没有默认网关,因此,排除所有没有默认网关的IP。

 foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces()) { var addr = ni.GetIPProperties().GatewayAddresses.FirstOrDefault(); if (addr != null) { if (ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet) { Console.WriteLine(ni.Name); foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses) { if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { Console.WriteLine(ip.Address.ToString()); } } } } } 

使用WMI并检查物理设备的ConnectorPresent属性。

 public static string GetPhysicalIPAdress() { foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces()) { if (ConnectorPresent(ni)) { if (ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet) { foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses) { if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { return ip.Address.ToString(); } } } } } return string.Empty; } private static bool ConnectorPresent(NetworkInterface ni) { ManagementScope scope = new ManagementScope(@"\\localhost\root\StandardCimv2"); ObjectQuery query = new ObjectQuery(String.Format( @"SELECT * FROM MSFT_NetAdapter WHERE ConnectorPresent = True AND DeviceID = '{0}'", ni.Id)); ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query); ManagementObjectCollection result = searcher.Get(); return result.Count > 0; }