简体   繁体   English

在所有NIC上使用IPv4和IPv6广播UDP消息

[英]Broadcast UDP message using IPv4 and IPv6 on all NICs

I am writing a couple of functions to allow me to send out a UDP broadcast / multicast using both IPv4 and IPv6. 我正在编写几个函数,以允许我同时使用IPv4和IPv6发送UDP广播/多播。 The follow code does this. 以下代码执行此操作。 The problem I have is that it only does this for a single adapter. 我的问题是,它仅对单个适配器执行此操作。 If I have two network adapters fitted to my PC it doesn't send the broadcast out on both. 如果我的PC上装有两个网络适配器,则不会在两个适配器上都发送广播。 Is it possible to have a single socket configured to handle both IPv4 and IPv6 and to send and receive on all NICs? 是否可以将单个套接字配置为同时处理IPv4和IPv6并在所有NIC上发送和接收? Or do I have to create separate sockets for each IP address? 还是我必须为每个IP地址创建单独的套接字?

    public void CreateBroadcaster(CancellationToken cancellationToken, int discoveryPort, int advancePort)
    {
        _cancellationToken = cancellationToken;

        _broadcastEndpoint = new IPEndPoint(IPAddress.Broadcast, advancePort);

        var epLocal = new IPEndPoint(IPAddress.IPv6Any, discoveryPort);

        _broadcaster = new UdpClient(epLocal);

        var soc = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp);
        soc.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false);

        _broadcaster.Client = soc;

        _broadcaster.Client.DualMode = true;

        _broadcaster.Client.Bind(epLocal);

        _broadcaster.EnableBroadcast = true;
        _broadcaster.MulticastLoopback = true;

        _broadcaster.Client.SetSocketOption(
            SocketOptionLevel.IPv6,
            SocketOptionName.AddMembership,
            new IPv6MulticastOption(IPAddress.Parse("ff02::1")));
    }

    public void SendPingsOnAdapterLocalSubnets()
    {
        _broadcaster.Send(_sendData, _sendData.Length, _broadcastEndpoint);
    }

You need 2 separate sockets. 您需要2个独立的插槽。 On the low level, the sockaddr struct will have one or other. 在较低级别,sockaddr结构将具有一个或另一个。 IPv4(AF_INET) or IPv6(AF_INET6). IPv4(AF_INET)或IPv6(AF_INET6)。

http://www.gnu.org/software/libc/manual/html_node/Address-Formats.html#Address-Formats http://www.gnu.org/software/libc/manual/html_node/Address-Formats.html#Address-Formats

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM