netutils.nim 480 B

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