如何在C#(IGMPv3)中加入源特定组播组

时间:2011-02-28 18:10:21

标签: c# sockets multicast igmp

我们有一个C#应用程序,可以加入和接收来自多播组的数据。这很好用。我们现在想要支持IGMPv3并且能够在加入多播组时指定源的IP。从MSDN文档中,我看不到如何执行此操作。我发现以下链接似乎回答了我的问题。

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

以下是我实施此方法的方法:

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);

但是在使用此错误调用SetSocketOption()时出现SocketException:The requested address is not valid in its context

有人能指出我在这里做错了吗?谢谢!

2 个答案:

答案 0 :(得分:5)

链接状态为SocketOptionName.AddSourceMembership,您正在使用AddMembership

答案 1 :(得分:0)

对于那些在源多播中挣扎的人

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);
        }
    });
}