在一台同时具有事件无线网卡和 LAN 端口并通过交叉电缆连接到另一台运行相同应用程序的计算机的计算机上,我们需要通过 LAN 线向另一台计算机发送 UDP 多播。使用 C# 套接字,Windows 似乎每次都尝试通过 WLAN 适配器路由消息。
有没有办法指定在哪个网络接口(interface)上发送 UDP 多播?
最佳答案
正如 Nikolai 回答的附录:KB318911 的问题是一个肮脏的把戏,用户必须提供必要的适配器索引。在寻找如何检索此适配器索引时,我想出了这样的方法:
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in nics)
{
IPInterfaceProperties ip_properties = adapter.GetIPProperties();
if (!adapter.GetIPProperties().MulticastAddresses.Any())
continue; // most of VPN adapters will be skipped
if (!adapter.SupportsMulticast)
continue; // multicast is meaningless for this type of connection
if (OperationalStatus.Up != adapter.OperationalStatus)
continue; // this adapter is off or not connected
IPv4InterfaceProperties p = adapter.GetIPProperties().GetIPv4Properties();
if (null == p)
continue; // IPv4 is not configured on this adapter
// now we have adapter index as p.Index, let put it to socket option
my_sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, (int)IPAddress.HostToNetworkOrder(p.Index));
}
完整注释在 http://windowsasusual.blogspot.ru/2013/01/socket-option-multicast-interface.html
关于c# - 在 .NET 中指定 UDP 多播应该转到的网络接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2192548/