add getPort to resolve Port(0) (#17559)

* add getPort to resolve Port(0)

* fixup

* use getPort in examples + tests

* address comments: do not re-export Port
This commit is contained in:
Timothee Cour 2021-03-30 11:14:39 -07:00 • committed by GitHub
commit 72988509ba
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 32 additions and 18 deletions

View file

@ -1,6 +1,7 @@
import std/[nativesockets, asyncdispatch, os]
proc bindAvailablePort*(handle: SocketHandle, port = Port(0)): Port =
## See also `asynchttpserver.getPort`.
block:
var name: Sockaddr_in
name.sin_family = typeof(name.sin_family)(toInt(AF_INET))
@ -8,5 +9,5 @@ proc bindAvailablePort*(handle: SocketHandle, port = Port(0)): Port =
name.sin_addr.s_addr = htonl(INADDR_ANY)
if bindAddr(handle, cast[ptr SockAddr](addr(name)),
sizeof(name).Socklen) < 0'i32:
raiseOSError(osLastError())
raiseOSError(osLastError(), $port)
result = getLocalAddr(handle, AF_INET)[1]