c# - 在 .NET 中指定 UDP 多播应该转到的网络接口(interface)

标签 c# .net sockets udp multicast

在一台同时具有事件无线网卡和 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/

相关文章:

c# - C# 中的 "var"是否类似于 C 中的 "size_t"?

c# - 如何比较厚度?

.net - 从 PDF 页面获取文本时出现 iTextSharp 异常 "Stack empty"

c# - 为什么我在 XAML 中填充的通用列表在运行时为空?

c# - 如何中止套接字的 BeginReceive()?

c# - 使用 Fluent Validation 验证输入字符串的某些部分

C# 枚举包含值

c# - 通过 SOS 调查 CLR

c - 允许多个套接字监听同一个端口有什么好处?

java序列化套接字输入流刷新