问题
On a Windows 7 VM, I am trying to send UDP packets to a multicast address using the second (non-default) of two network interfaces. I can achieve this with mcast using the /INTF option (which doesn't allow specifying the port), but my C# code doesn't work:
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
}
When I specify nicaddrstr
as the default network interface IP address, data flows as expected on that interface. However, if I specify nicaddrstr
as the second (non-default) network interface IP address, no data flows (as verified by Wireshark), even though no error is thrown in any function call. Can someone tell me what mcast is doing that allows the non-default NIC to accept the UDP data?
I've tried various combinations of route settings in the route table, but the contents don't seem to affect the behavior of this code.
来源:https://stackoverflow.com/questions/32750878/cant-send-multicast-over-non-default-nic