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.
Lightweight UDP library for Dart. Please file feature requests and bugs at the issue tracker. Lightweight, efficient, and easy-to-use UDP library for Dart. Supports Unicast, Broadcast, Multicast and Loopback communications.
Please file feature requests and bugs at the issue tracker. Lightweight, efficient, and easy-to-use UDP library for Dart. Supports Unicast, Broadcast, Multicast and Loopback communications.
Thanks in advance for you help. Broadcast UDP is often blocked by network devices due to the load it causes. Consider using multicast to get a message out to multiple receivers. Use InternetAddress.anyIPv4 for binding on all network interfaces; Enable permission for broadcasting with property broadcastEnabled
An unbuffered interface to a UDP socket. The raw datagram socket delivers the datagrams in the same chunks as the underlying operating system. It's a Stream of RawSocketEvent s.
There are two problems:
Use InternetAddress.anyIPv4
for binding on all network interfaces;
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);
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With