summary refs log tree commit diff stats
path: root/lib/pure/nativesockets.nim
diff options
context:
space:
mode:
authorrockcavera <rockcavera@gmail.com>2020-06-27 18:59:08 -0300
committerGitHub <noreply@github.com>2020-06-27 22:59:08 +0100
commit252f668829ee15f91c9c7febd6cec8e9a85d6fc7 (patch)
tree713ad5ca3e549464ef47967bbe5d1ce1d156721f /lib/pure/nativesockets.nim
parentbc66788b3fbe0a312ddd4e1c2d58e902787ca512 (diff)
downloadNim-252f668829ee15f91c9c7febd6cec8e9a85d6fc7.tar.gz
add a second asyncnet.recvFrom (#14237)
* add a second asyncnet.recvFrom

* fixes

* pre-allocating address

* add a new nativesockets.getAddrString()
Diffstat (limited to 'lib/pure/nativesockets.nim')
-rw-r--r--lib/pure/nativesockets.nim34
1 files changed, 34 insertions, 0 deletions
diff --git a/lib/pure/nativesockets.nim b/lib/pure/nativesockets.nim
index 67e24eedc..35a7396b9 100644
--- a/lib/pure/nativesockets.nim
+++ b/lib/pure/nativesockets.nim
@@ -461,6 +461,40 @@ proc getAddrString*(sockAddr: ptr SockAddr): string =
         return "unix"
     raise newException(IOError, "Unknown socket family in getAddrString")
 
+proc getAddrString*(sockAddr: ptr SockAddr, strAddress: var string) =
+  ## Stores in ``strAddress`` the string representation of the address inside
+  ## ``sockAddr``
+  ## 
+  ## **Note**
+  ## * ``strAddress`` must be initialized to 46 in length.
+  assert(46 == len(strAddress),
+         "`strAddress` was not initialized correctly. 46 != `len(strAddress)`")
+  if sockAddr.sa_family.cint == nativeAfInet:
+    let addr4 = addr cast[ptr Sockaddr_in](sockAddr).sin_addr
+    when not useWinVersion:
+      if posix.inet_ntop(posix.AF_INET, addr4, addr strAddress[0],
+                         strAddress.len.int32) == nil:
+        raiseOSError(osLastError())
+    else:
+      if winlean.inet_ntop(winlean.AF_INET, addr4, addr strAddress[0],
+                           strAddress.len.int32) == nil:
+        raiseOSError(osLastError())
+  elif sockAddr.sa_family.cint == nativeAfInet6:
+    let addr6 = addr cast[ptr Sockaddr_in6](sockAddr).sin6_addr
+    when not useWinVersion:
+      if posix.inet_ntop(posix.AF_INET6, addr6, addr strAddress[0],
+                         strAddress.len.int32) == nil:
+        raiseOSError(osLastError())
+      if posix.IN6_IS_ADDR_V4MAPPED(addr6) != 0:
+        strAddress = strAddress.substr("::ffff:".len)
+    else:
+      if winlean.inet_ntop(winlean.AF_INET6, addr6, addr strAddress[0],
+                           strAddress.len.int32) == nil:
+        raiseOSError(osLastError())
+  else:
+    raise newException(IOError, "Unknown socket family in getAddrString")
+  setLen(strAddress, len(cstring(strAddress)))
+
 when defined(posix) and not defined(nimdoc):
   proc makeUnixAddr*(path: string): Sockaddr_un =
     result.sun_family = AF_UNIX.TSa_Family