如果套接字绑定到0.0.0.0,为什么我不能向组播地址发送消息。对于ipv6套接字,它的工作原理

时间:2017-02-19 07:03:28

标签: c# sockets networking ipv6 ipv4

我有两个套接字向组播发送消息,ipv6和ipv4

对于ipv6方法正常工作

对于ipv4,如果套接字没有绑定到直接地址,则它不起作用。

为什么要指定创建套接字的地址

IPV6:

    private static void SendToMulticastIpv6()
    {
        var socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp);
        socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.MulticastTimeToLive, 10);
        socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.AddMembership, new IPv6MulticastOption(IPAddress.Parse("ff02::c")));

        socket.Bind(new IPEndPoint(IPAddress.IPv6Any, 0));

        socket.SendTo(Encoding.UTF8.GetBytes("message"), new IPEndPoint(IPAddress.Parse("ff02::c"), 1900));

        Console.WriteLine("done v6");
    }

IPV4:

    private static void SendToMulticastIpv4()
    {
        var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 10);
        socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership,
            new MulticastOption(IPAddress.Parse("239.255.255.250")));

        //Does not works
        //socket.Bind(new IPEndPoint(IPAddress.Any, 0));

        //I need to specify the my address
        socket.Bind(new IPEndPoint(IPAddress.Parse("192.168.100.100"), 0));

        socket.SendTo(Encoding.UTF8.GetBytes("message"), new IPEndPoint(IPAddress.Parse("239.255.255.250"), 1900));

        Console.WriteLine("done v4");
    }

0 个答案:

没有答案