Search code examples
socketsdartudpbroadcast

Dart - Send an UDP broadcast


I'm asking for help since it seems I cannot find a way to send an UDP broadcast inside a local network using Dart.

So far I managed to communicate using UDP with RawDatagramSocket. I'm able to send a message to a specific address.

What I'm not able to do is to send a broadcast to any device inside a local network (network mask is 255.255.255.0), and to wait for possible (multiple) answer(s). Here is the code I'm using:

RawDatagramSocket.bind('127.0.0.1', 8889)
    .then((RawDatagramSocket udpSocket) {
        udpSocket.listen((e) {
            Datagram dg = udpSocket.receive();
            if (dg != null) {
                //stuff
            }
        });
        udpSocket.send(utf8.encode('TEST'), DESTINATION_ADDRESS, 8889);
});

I tried to replace DESTINATION_ADDRESS with InternetAddress.anyIPv4, but I had no luck. I also found the property broadcastEnabled inside RawDatagramSocket, but I cannot find further informations about how to make use of it.

Thanks in advance for you help.


Solution

  • There are two problems:

    1. Use InternetAddress.anyIPv4 for binding on all network interfaces;

    2. Enable permission for broadcasting with property broadcastEnabled

    Obviously use a broadcast address: for a /24 network use x.y.z.255 address.

    This snippet works:

    import 'dart:io';
    import 'dart:convert';
    
    main() {
    
      var DESTINATION_ADDRESS=InternetAddress("x.y.z.255");
    
      RawDatagramSocket.bind(InternetAddress.anyIPv4, 8889).then((RawDatagramSocket udpSocket) {
        udpSocket.broadcastEnabled = true;
        udpSocket.listen((e) {
          Datagram dg = udpSocket.receive();
          if (dg != null) {
            print("received ${dg.data}");
          }
        });
        List<int> data =utf8.encode('TEST');
        udpSocket.send(data, DESTINATION_ADDRESS, 8889);
      });
    }