Is there a `getsockname` for `UDPSocket`?

I’m trying to write some simple program that involves communication with UDP sockets. I would like not to manually bind the port to the socket, and let the OS choose it. It can be achieved by binding to port 0. However, I do not see a way to retrieve the port number from the UDPSocket struct. Function getsockname that can do it is exclusively for TCPSocket.

using Sockets

socket = UDPSocket()
bind(socket, ip"0.0.0.0", 0)

getsockname(socket) # It only works for TCP sockets

close(socket)

Is there any proper way to retrieve the port? I only have hacky approaches, that involves sending one packet to second socket, but that’s just bad. :slight_smile:

Looks like the wrapper for uv_udp_getsockname is missing, the TCP one is here. As a (possibly worse than what you are doing) hack, you can call it directly:

julia> socket = UDPSocket()
UDPSocket(init)

julia> bind(socket, ip"0.0.0.0", 0)
true

julia> size = Ref{Int64}(16)
Base.RefValue{Int64}(16)

julia> sockaddr = zeros(UInt16, 8)
8-element Vector{UInt16}:
 0x0000
 0x0000
 0x0000
 0x0000
 0x0000
 0x0000
 0x0000
 0x0000

julia> @ccall uv_udp_getsockname(socket.handle::Ptr{Cvoid}, sockaddr::Ptr{Cvoid}, size::Ptr{Int64})::Cint
0

julia> Int(ntoh(sockaddr[2]))
54592

1 Like

That’s a bummer it is missing.

The solution your propose is nice, certainly better than what I did, thanks. :smiley:

Can you create an issue at: GitHub · Where software is built so that the developers are informed that this should be added?