AdamDSmith42
AdamDSmith42

Reputation: 23

UDP multicast listener picking up messages from incorrect multicast group

I am writing a service that sends multicast messages for communication between multiple instances of my service across a network. I am setting up two listeners and sending the messages twice (239.1.1.1 on the primary NIC, 239.1.1.2 on the secondary NIC) Everything works fine, but occasionally the secondary listener, on the .2 multicast group will pick up messages sent to the .1 multicast group. Any idea why this might be happening?

Here is how I am setting up my listeners:

PrimaryLocalEP = new IPEndPoint(primaryNIC.Address, vnc.DefaultUtilityPort);
PrimaryClient.ExclusiveAddressUse = false;
PrimaryClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
PrimaryClient.Client.Bind(PrimaryLocalEP);
PrimaryClient.JoinMulticastGroup(IPAddress.Parse("239.1.1.1"), primaryNIC.Address);
PrimaryClient.MulticastLoopback = false;
PrimaryRemoteEP = new IPEndPoint(IPAddress.Parse("239.1.1.1"), vnc.DefaultUtilityPort);

ReadThread = new System.Threading.Thread(ReadConnection);
ReadThread.IsBackground = true;
ReadThread.Name = "UDPReadConnection";
ReadThread.Start();


SecondaryLocalEP = new IPEndPoint(secondaryNIC.Address, vnc.DefaultUtilityPort);
SecondaryClient.ExclusiveAddressUse = false;
SecondaryClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
SecondaryClient.Client.Bind(SecondaryLocalEP);
SecondaryClient.JoinMulticastGroup(IPAddress.Parse("239.1.1.2"), secondaryNIC.Address);
SecondaryClient.MulticastLoopback = false;
SecondaryRemoteEP = new IPEndPoint(IPAddress.Parse("239.1.1.2"), vnc.DefaultUtilityPort);

ReadThreadSecondary = new System.Threading.Thread(ReadSecondaryConnection);
ReadThreadSecondary.IsBackground = true;
ReadThreadSecondary.Name = "UDPReadConnectionSecondary";
ReadThreadSecondary.Start();

Upvotes: 0

Views: 1138

Answers (2)

Yury Schkatula
Yury Schkatula

Reputation: 5369

This happens due the fact that by default only one NIC is multicast listener (picked up by OS due internal algorithm depending on interface priority so any VPN connection established can cause a problem then). You have to explicitly set SocketOptionName.MulticastInterface for the given NIC to involve it into multicast listening all the time.

Upvotes: 0

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84159

Short answer - put them on different ports.

What basically happens is that after NIC hardware identified that packet needs to be delivered, i.e. there's a process on the box with membership in given multicast group, the OS network stack only uses the port number to identify the process waiting for UDP input. It's essentially random which one out of your two listening processes gets the packet.

Upvotes: 1

Related Questions