C# 套接字发送 // 将 UDP 多播绑定到选定的网络接口



您好,我的 PC 上有 2 个网络适配器,并希望将 udp 组播发送到所选网络接口上的组 239.0.0.222 端口 9050。但它仅适用于第一个接口,当选择另一个 NIC 时,不会发送任何数据。

本地 IP 是所选适配器中的本地 IP

发件人代码:

 IPAddress localIP = getLocalIpAddress();
 IPAddress multicastaddress = IPAddress.Parse("239.0.0.222");
 IPEndPoint remoteep = new IPEndPoint(multicastaddress, 9050);
 UdpClient udpclient = new UdpClient(9050);
 MulticastOption mcastOpt = new MulticastOption(multicastaddress,localIP);
 udpclient.Client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, mcastOpt);
 udpclient.Send(data, data.Length, remoteep);

编辑1:
适配器本地 IP 的代码:

NetworkInterface.GetAllNetworkInterfaces()[adapterIndex].GetIPProperties().UnicastAddresses[0].Address;

编辑2,5:
也尝试了相同的重用Wireshark 向我显示第二个适配器上组播组的正确联接

udpclient.JoinMulticastGroup(multicastaddress);
udpclient.Client.Bind(remoteep);

编辑3:
我现在在另一台 PC 上尝试,但同样的问题再次发生,适配器 1 运行,在所有其他 PC 上没有发送任何内容。
我尝试的另一件事是在 windows xp 配置中切换前两个适配器的顺序,然后新的第一个适配器再次工作,但新的第二个适配器不发送任何内容。

默认情况下,只有第一个适配器加入给定的多播组。从操作系统的角度来看,这是绝对相关的,因为无论适配器使用多播流,该组都将提供相同的内容。如果计划在每个适配器上侦听多播,则必须遍历它们并在每个适配器上放置适当的套接字选项:

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
  my_sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, (int)IPAddress.HostToNetworkOrder(p.Index));
}

附言是的,我是@lukebuehler提到的"这个人":http://windowsasusual.blogspot.ru/2013/01/socket-option-multicast-interface.html

我认为这家伙有答案,您必须遍历网络接口并找到支持多播的接口。

http://windowsasusual.blogspot.ru/2013/01/socket-option-multicast-interface.html

最新更新