I'm using flutter and utilising the RawDatagramSocket in dart in order to send a WOL packet. My code works fine in IOS but in the android emulator I keep getting this error
Unhandled Exception: SocketException: Failed to create datagram socket (OS Error: Permission denied, errno = 13), address = 0.0.0.0, port = 9
I have these permissions in my android manifest but I still can't get it to stop erroring:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Example of usage is shown below:
class WakeOnLanService {
Future wake(InternetAddress ipAddress, MacAddress macAddress, int port) {
return RawDatagramSocket.bind(InternetAddress.anyIPv4, port)
.then((RawDatagramSocket udpSocket) {
udpSocket.broadcastEnabled = true;
List<int> macBytes = macAddress.bytes;
List<int> packet = new List<int>(17 * 6);
for (int i = 0; i < 6; i++) packet[i] = 0xFF;
for (int i = 1; i <= 16; i++)
for (int j = 0; j < 6; j++) packet[i * 6 + j] = macBytes[j];
udpSocket.send(packet, ipAddress, port);
udpSocket.close();
});
}
}
To use ephemeral port (like in java, as mentioned in comments) just pass 0 to bind.
return RawDatagramSocket.bind(InternetAddress.anyIPv4, 0)
It's not documented, here is an issue: https://github.com/dart-lang/sdk/issues/35147
Quote:
If port has the value 0 an ephemeral port will be chosen by the system. The actual port used can be retrieved using the port getter.