以Broadcasting UDP message to all the available network cards为例,我创建了一个封装了上述问题的merce_00答案的类。本质上,它枚举了按如下方式获得的每个单播地址上广播的接口:
var ethip4NetworkInterfaces =
from ni in NetworkInterface.GetAllNetworkInterfaces()
where ni.Supports(NetworkInterfaceComponent.IPv4) &&
(
ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet ||
ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet3Megabit ||
ni.NetworkInterfaceType == NetworkInterfaceType.FastEthernetFx ||
ni.NetworkInterfaceType == NetworkInterfaceType.FastEthernetT ||
ni.NetworkInterfaceType == NetworkInterfaceType.GigabitEthernet
)
select ni;
var unicastAddresses = (
from nic in ethip4NetworkInterfaces
from ua in nic.GetIPProperties().UnicastAddresses
where ua.Address.AddressFamily == AddressFamily.InterNetwork
select ua.Address
).ToArray();
在测试过程中,我遇到了一个描述为SocketError
的{{1}}
像这样排除以169开头的单播地址
The selected IP address is not valid in this context.
允许我的测试通过,但是我希望知道此错误的具体条件,以便使该实用程序可靠。
var unicastAddresses = (
from nic in ethip4NetworkInterfaces
from ua in nic.GetIPProperties().UnicastAddresses
where ua.Address.AddressFamily == AddressFamily.InterNetwork
&& ua.Address.GetAddressBytes()[0] != 169
select ua.Address
).ToArray();
块吗?循环选项将支票委托给try
。这肯定是正确的,但并不完美。
将构造包装到异常处理程序中的工厂方法会将空值放在发出的集合中,该空值可以由另一个where子句删除,但比循环长 。
有人可以在循环/尝试选项上进行改进吗?