How to join source specific multicast group in C#

2019-01-26 02:04发布

问题:

We have a C# application that can join and receives data from a multicast group. This works well. We now want to support IGMPv3 and be able to specify the IP of the source when joining a multicast group. From the MSDN documentation, I don't see how to do this. I have found the following link that seems to answer my question.

http://social.msdn.microsoft.com/Forums/en/netfxnetcom/thread/e8063f6d-22f5-445e-a00c-bf46b46c1561

And here is how I implemented this:

byte[] membershipAddresses = new byte[12]; // 3 IPs * 4 bytes (IPv4)
Buffer.BlockCopy(multicastIp.GetAddressBytes(), 0, membershipAddresses, 0, 4);
Buffer.BlockCopy(sourceIp.GetAddressBytes(), 0, membershipAddresses, 4, 4);
Buffer.BlockCopy(localIp.GetAddressBytes(), 0, membershipAddresses, 8, 4);
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, membershipAddresses);

But I get a SocketException when calling SetSocketOption() with this error: The requested address is not valid in its context.

Can someone points me what I am doing wrong here? Thanks!

回答1:

The link states SocketOptionName.AddSourceMembership, you are using AddMembership.