How to initialize `UDPSocket` for broadcast?

What is the correct way to initialize a UDPSocket for only sending broadcast packets?

I wondered if this would work:

julia> usock=UDPSocket()
UDPSocket(init)

julia> send(usock, ip"255.255.255.255", 42000, "test")
ERROR: IOError: send: permission denied (EACCES)
Stacktrace:
 [1] uv_error at .\libuv.jl:85 [inlined]
 [2] send(::UDPSocket, ::IPv4, ::Int64, ::String) at C:\cygwin\home\Administrator\buildbot\worker\package_win64\build\usr\share\julia\stdlib\v1.0\Sockets\src\Sockets.jl:354
 [3] top-level scope at none:0

And that error makes sense. On v1.0.1, I tried to use Sockets.setopt and that yields a different issue:

julia> usock=UDPSocket()
UDPSocket(init)

julia> Sockets.setopt(usock; enable_broadcast=true)
ERROR: IOError: enable_broadcast: bad file descriptor (EBADF)
Stacktrace:
 [1] uv_error at .\libuv.jl:85 [inlined]
 [2] #setopt#4 at C:\cygwin\home\Administrator\buildbot\worker\package_win64\build\usr\share\julia\stdlib\v1.0\Sockets\src\Sockets.jl:266 [inlined]
 [3] (::getfield(Sockets, Symbol("#kw##setopt")))(::NamedTuple{(:enable_broadcast,),Tuple{Bool}}, ::typeof(Sockets.setopt), ::UDPSocket) at .\none:0
 [4] top-level scope at none:0

I can get around this by:

  1. Making a UDPSocket
  2. Sending a ‘throw-away’ packet to localhost
  3. Using Sockets.setopt, set enable_broadcast = true
  4. Finally send a packet on the broadcast address

I’ve confirmed this works (see below), but is this the preferred way to actually set up and use a UDPSocket for broadcast?

On the receive side:

julia> using Sockets

julia> usock=UDPSocket()
UDPSocket(init)

julia> bind(usock, ip"0.0.0.0", 42000)
true

julia> apkt = String(recv(usock))
"actual_payload"

julia>

On the send side:

julia> using Sockets

julia> usock=UDPSocket()
UDPSocket(init)

julia> send(usock, ip"127.0.0.1", 0, "test")

julia> Sockets.setopt(usock; enable_broadcast=true)

julia> send(usock, ip"255.255.255.255", 42000, "actual_payload")

julia>

You can use a bind() in place of the throw away packet, setopt needs an initialized socket i think

Can multiple applications bind to the same UDP socket?

There’s a reuseaddr = false as the default, and it says only the last to bind to an address receives traffic, so they should be transmit only but yes
see the >?bind last paragraph for a bit more info