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

前端 未结 2 1576
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-18 15:19

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 w

相关标签:
2条回答
  • 2020-12-18 15:47

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

    0 讨论(0)
  • 2020-12-18 16:05

    For anyone 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);
            }
        });
    }
    
    0 讨论(0)
提交回复
热议问题