在具有活动无线卡和LAN端口的计算机上,交叉电缆连接到运行相同应用程序的另一台计算机,我们需要通过LAN线路将UDP多播发送到另一台计算机.使用C#套接字,Windows似乎每次尝试通过WLAN适配器路由消息.
有没有办法指定发送UDP多播的网络接口?
就像尼古拉的补遗一样: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