当前位置: 首页 > 编程语言 > C#

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

时间:2023-04-10 14:17:44 C#

C#-查找我机器的本地IP地址而不是VM我的机器上安装了VirtualBoxVM,因此有一个以太网适配器用于它被显示。我通过以下方式枚举了我机器的IP地址列表:publicstringGetLocalIpAddress(){try{stringstrHostName=Dns.GetHostName();//Thenusinghostname,gettheIPaddresslist..IPHostEntryipEntry=Dns.GetHostEntry(strHostName);foreach(IPAddressipinipEntry.AddressList){if(ip.AddressFamily==System.Net.Sockets.AddressFamily.InterNetwork){returnstring.Format("({0})",ip.ToString());}}}catch(Exceptione){Global.ApplicationLog.AddApplicationLog(EnumAppEventTypes.SYSTEM_ERROR,e.ToString());}返回””;我的问题是虚拟机的以太网适配器也捕获了条件:if(ip.AddressFamily==System.Net.Sockets.AddressFamily.InterNetwork)Isthereawaytopickoutmymachine'slocalIPaddressandignoremyVM?您可以按名称忽略以太网适配器。由于VM以太网适配器由有效的NIC驱动程序表示,因此从操作系统的角度来看,它完全等同于机器的物理网卡。我正在改进AndrejArh的回答,因为GatewayAddresses报告的IP地址也可以是“0.0.0.0”而不是null:GetIPProperties().GatewayAddresses.FirstOrDefault();if(addr!=null&&!addr.Address.ToString().Equals("0.0.0.0")){if(ni.NetworkInterfaceType==NetworkInterfaceType.Wireless80211||ni.NetworkInterfaceType==NetworkInterfaceType.Ethernet){foreach(unicastIPAddressInformationipinni.GetIPProperties().UnicastAddresses){if(ip.Address.AddressFamily==AddressFamily.InterNetwork){returnip.Address.ToString();}}}}}}返回String.Empty;有一个选择。VMIP没有默认网关,因此排除所有没有默认网关的IP。foreach(NetworkInterfaceniinNetworkInterface.GetAllNetworkInterfaces()){varaddr=ni.GetIPProperties().GatewayAddresses.FirstOrDefault();if(addr!=null){if(ni.NetworkInterfaceType==NetworkInterfaceType.Wireless80211||ni.NetworkInterfaceType==NetworkInterfaceType.Ethernet){Console.WriteLine(ni.Name);foreach(UnicastIPAddressInformationipinni.GetIPProperties().UnicastAddresses){如果(ip.Address.AddressFamily==System.Net.Sockets.AddressFamily.InterNetwork){Console.WriteLine(ip.Address.ToString());}}}}}使用WMI并检查物理设备的ConnectorPresent属性。以上就是C#学习教程:C#——查找我机器的本地IP地址而不是VM分享的全部内容。如果对大家有用,需要详细了解C#学习教程,希望大家多多关注——publicstaticstringGetPhysicalIPAdress(){){if(ni.NetworkInterfaceType==NetworkInterfaceType.Wireless80211||ni.NetworkInterfaceType==NetworkInterfaceType.Ethernet){foreach(UnicastIPAddressInformationipinni.GetIPProperties().UnicastAddresses){if(ip.Address.AddressFamily==System.Net.Sockets.AddressFamily.InterNetwork){返回ip.Address.ToString();}}}}}返回字符串。空;}privatestaticboolConnectorPresent(NetworkInterfaceni){ManagementScopescope=newManagementScope(@"\localhostrootStandardCimv2");ObjectQueryquery=newObjectQuery(String.Format(@"SELECT*FROMMSFT_NetAdapterWHERECon??nectorPresent=TrueANDDeviceID='{0}'",ni.Id));ManagementObjectSearcher搜索器=newManagementObjectSearcher(范围,查询);ManagementObjectCollection结果=searcher.Get();返回结果.Count>0;}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: