在具有多个IPv4地址的环境中,如何选择要侦听的地址?我对以下代码感到好运:
foreach(IPAddress addr in Dns.GetHostAddresses(Dns.GetHostName()))
if (addr.AddressFamily == AddressFamily.InterNetwork)
if (!IPAddress.IsLoopback(addr))
return addr.ToString();
由于它不认为以下接口适配器是环回地址:
Ethernet adapter loopback:
Connection-specific DNS Suffix . :
Description . . . . . . . . . . . : Microsoft Loopback Adapter
Physical Address. . . . . . . . . : XX.XX.XX.XX.XX.XX
DHCP Enabled. . . . . . . . . . . : Yes
Autoconfiguration Enabled . . . . : Yes
Autoconfiguration IPv4 Address. . : 169.254.XXX.XXX(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.0.0
Default Gateway . . . . . . . . . :
DNS Servers . . . . . . . . . . . : XXX: XXX: XXX:XXXX::XXX
XXX: XXX: XXX:XXXX::XXX
XXX: XXX: XXX:XXXX::XXX
NetBIOS over Tcpip. . . . . . . . : Enabled
我见过一些程序员假设存在名为“Local Area Connection”的NetworkInterface
并且始终是正确的接口,但我认为这不是正确的方法。
答案 0 :(得分:1)
我认为没有任何感觉过滤接口,因为您可能在设备上有多个卡(例如以太网和wifi)。如果您正在开发服务器组件,那么您肯定希望获得他们使用的任何接口的所有请求。