【发布时间】:2013-05-06 14:50:22
【问题描述】:
在具有多个 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 并且始终是正确的接口,但我认为这不是正确的方法。
【问题讨论】:
-
你为什么不在所有接口上听呢?这就是大多数服务器应用程序所做的,除非它们被配置为不这样做。
-
Heinzi++ :) 在这种情况下使用
IPAddress.Any作为 IP 地址。 -
如有疑问,请监听所有接口。如果您只需要某个 IP 地址,用户应该选择它(就像在 Wireshark 中所做的那样)。否则软件无法知道其意图。
标签: c# ip-address