在.NET中指定UDP多播应该使用的网络接口

Mar*_*oth 11 .net c# sockets udp multicast

在具有活动无线卡和LAN端口的计算机上,交叉电缆连接到运行相同应用程序的另一台计算机,我们需要通过LAN线路将UDP多播发送到另一台计算机.使用C#套接字,Windows似乎每次尝试通过WLAN适配器路由消息.

有没有办法指定发送UDP多播的网络接口?

Yur*_*ula 15

就像尼古拉的补遗一样: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));
}
Run Code Online (Sandbox Code Playgroud)

完整说明http://windowsasusual.blogspot.ru/2013/01/socket-option-multicast-interface.html

  • 为IPv6执行此操作时浪费了很多时间,所以只需要抬头:当使用SocketOptionLevel.IPv6在IPv6套接字上设置时,接口索引应以主机字节顺序传递.在IPv4上设置时,它应该是网络字节顺序,这很容易错过.IPv6选项:https://msdn.microsoft.com/en-us/library/windows/desktop/ms738574(v = vs.85).aspx IPv4选项:https://msdn.microsoft.com/en-us/库/窗/桌面/ ms738586(v = vs.85)的.aspx (4认同)

Nik*_*sov 5

你可能正在寻找SocketOptionName.MulticastInterface.这里的MSDN上的一篇文章,可以帮助你.

除此之外,如果您更新本地路由表以获得与多播地址匹配的精确条目并指向正确的接口,那么它应该正常工作.

  • 链接已损坏。这个答案是没有用的。 (5认同)