C# Can';t通过非默认NIC发送多播

C# Can';t通过非默认NIC发送多播,c#,windows,sockets,networking,multicast,C#,Windows,Sockets,Networking,Multicast,在Windows7VM上,我尝试使用两个网络接口中的第二个(非默认)向多播地址发送UDP数据包。我可以使用/INTF选项(不允许指定端口)通过mcast实现这一点,但我的C#代码不起作用: void run(string ipaddrstr, int port, string nicaddrstr) { int index = -1; // Create a socket for the UDP broadcast Socket socket = new Socket(A

在Windows7VM上,我尝试使用两个网络接口中的第二个(非默认)向多播地址发送UDP数据包。我可以使用/INTF选项(不允许指定端口)通过mcast实现这一点,但我的C#代码不起作用:

void run(string ipaddrstr, int port, string nicaddrstr)
{
    int index = -1;
    // Create a socket for the UDP broadcast
    Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    IPAddress ipaddr = IPAddress.Parse(ipaddrstr);
    IPAddress nicAddr = IPAddress.Parse(nicaddrstr);
    int i = 0;
    foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces()) {
        if (ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet) {
            foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses) {
                if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) {
                    if (ip.Address.Equals(nicAddr)) {
                        index = i;
                        break;
                    }
                }
            }
            if (index != -1) {
                break;
            }
            i++;
        }
        if (index == -1) {
            Console.Error.WriteLine("Couldn't find NIC with IP address '" + nicaddrstr + "'");
            return;
        }
        socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ipaddr, nicAddr));
        int multicastInterfaceIndex = (int)IPAddress.HostToNetworkOrder(index);
        socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, multicastInterfaceIndex);
    }
    socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 1);

    IPEndPoint endpoint = new IPEndPoint(ipaddr, port);
    socket.Connect(endpoint);
    // At this point, data can be send to the socket
}
当我指定
nicaddrstr
作为默认网络接口IP地址时,数据在该接口上按预期流动。但是,如果我指定
nicaddrstr
作为第二个(非默认)网络接口IP地址,则不会有数据流(由Wireshark验证),即使在任何函数调用中都不会引发错误。有人能告诉我mcast是如何允许非默认NIC接受UDP数据的吗


我在route表中尝试了各种路由设置组合,但内容似乎不会影响此代码的行为。

有一次,我用
socket.Bind(IPAddressOfInterface,somePort)
Omg解决了这个问题,这些嵌套循环和ifs可以从一些LINQ中受益。很难相信10年前那个代码被认为是正确的。我很高兴你认识LINQ。这个评论如何帮助我解决我的问题?埃瑟,谢谢你的建议。在执行
socket.Connect
之前,我使用了
socket.bind(新的IPEndPoint(ipaddrofinterface,0))
,这很有效。