2

我们有一个 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:。

有人可以指出我在这里做错了什么吗?谢谢!

4

2 回答 2

5

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

于 2011-03-01T01:38:47.547 回答
1

对于任何为源多播而苦苦挣扎的人

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);
        }
    });
}
于 2019-05-28T16:21:07.570 回答