1

在具有多个 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

我见过一些程序员假设NetworkInterface存在一个名为“本地连接”并且始终是正确的接口,但我认为这不是正确的方法。

4

1 回答 1

1

I think there is no sense filtering interfaces as you may have multiple cards on a device (ethernet & wifi for instance). If you're developping a server component you will certainly want to get all the requests whatever interface they use.

于 2013-05-06T14:57:36.490 回答