How to join source specific multicast group in C# (IGMPv3)

故事扮演 提交于 2019-11-28 01:57:06

问题


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.




回答2:


For enyone struggling with source multicast

static void StartListner(IPAddress sourceIp, IPAddress multicastGroupIp, IPAddress localIp, int port)
{
    Task.Run(() =>
    {
        try
        {
            Console.WriteLine("Starting: "  + sourceIp + " - " + multicastGroupIp + " - " + localIp + " / " + port);

            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            IPEndPoint localEndpoint = new IPEndPoint(localIp, port);
            socket.Bind(localEndpoint);

            byte[] membershipAddresses = new byte[12]; // 3 IPs * 4 bytes (IPv4)
            Buffer.BlockCopy(multicastGroupIp.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.AddSourceMembership, membershipAddresses);

            while (true)
            {
                byte[] b = new byte[1024];
                int length = socket.Receive(b);

                Console.WriteLine("PORT: " + port + " : " + Encoding.ASCII.GetString(b, 0, length));
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    });
}


来源:https://stackoverflow.com/questions/5145804/how-to-join-source-specific-multicast-group-in-c-sharp-igmpv3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!