netutils.nim 528 B

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