Search code examples
.net.net-5udpclient

Unable to broadcast UDP message


I am trying to create a WPF application which communicates using UDP broadcast messages. I understand that I can send messages to 255.255.255.255 to broadcast the messages.

var s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

var broadcast = IPAddress.Parse("255.255.255.255");

var buffer = Encoding.ASCII.GetBytes(message.ToString());
var endPoint = new IPEndPoint(broadcast, 11000);

s.SendTo(buffer, endPoint);

However, I get the SocketException with the error message

An attempt was made to access socket in a way forbidden by its access permission.

It is not a UWP application, so not sure which permission or how do I give the permission?


Solution

  • Based on the exception, and lacking any actual code, never mind a minimal, reproducible example, the most likely explanation is that you've simply failed to configure the socket to enable broadcast messages.

    You can fix this in one of two ways. You can call the SetSocketOption() method directly, passing the SocketOptionName.Broadcast value, and a value of true:

    udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
    

    or, you can set the EnableBroadcast property, which will do that for you:

    udpClient.EnableBroadcast = true;