'.net 6 UDP broadcast exception

Following code raises exception Der Zugriff auf einen Socket war aufgrund der Zugriffsrechte des Sockets unzulässig. Access Denied 10013

 Dim s As Socket = New Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
 Dim sendbuf As Byte() = Encoding.ASCII.GetBytes("ppedv")
 Dim ep As IPEndPoint = New IPEndPoint(IPAddress.Broadcast, 21000) '255.255.255.255

 s.SendTo(sendbuf, ep)

change to broadcast like 192.255.255.255 works windows 11



Solution 1:[1]

Error 10013 is WSAEACCES. Per the Windows Sockets Error Codes documentation:

Return code/value Description
WSAEACCES
10013
Permission denied.
An attempt was made to access a socket in a way forbidden by its access permissions. An example is using a broadcast address for sendto without broadcast permission being set using setsockopt(SO_BROADCAST).
Another possible reason for the WSAEACCES error is that when the bind function is called (on Windows NT 4.0 with SP4 and later), another application, service, or kernel mode driver is bound to the same address with exclusive access. Such exclusive access is a new feature of Windows NT 4.0 with SP4 and later, and is implemented by using the SO_EXCLUSIVEADDRUSE option.

And per .NET's Socket.SendTo() documentation:

If you are using a connectionless protocol in blocking mode, SendTo will block until the datagram is sent. If you want to send data to a broadcast address, you must first call the SetSocketOption method and set the socket option to SocketOptionName.Broadcast. You must also be sure that the size does not exceed the maximum packet size of the underlying service provider. If it does, the datagram will not be sent and SendTo will throw a SocketException.

So, try this:

Dim s As Socket = New Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
Dim sendbuf As Byte() = Encoding.ASCII.GetBytes("ppedv")
Dim ep As IPEndPoint = New IPEndPoint(IPAddress.Broadcast, 21000) '255.255.255.255

s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, True) ' <-- add this!

s.SendTo(sendbuf, ep)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1