无法通过非默认NIC发送多播

时间:2015-09-23 23:04:38

标签: c# windows sockets networking multicast

在Windows 7 VM上,我尝试使用第二个(非默认)两个网络接口将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数据吗?

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

0 个答案:

没有答案