diff options
author | Federico Ceratto <federico.ceratto@gmail.com> | 2019-03-16 18:51:26 +0000 |
---|---|---|
committer | Federico Ceratto <federico.ceratto@gmail.com> | 2019-03-17 16:58:27 +0000 |
commit | 5825dcb0b5d6082322ae4d6e364a8c4d6f898b93 (patch) | |
tree | 96191f9d8cc118cce33563a440c79601a26dcfa6 /lib/pure/net.nim | |
parent | 328901757a2bb5d482afafdd0e45bd54355c90b5 (diff) | |
download | Nim-5825dcb0b5d6082322ae4d6e364a8c4d6f898b93.tar.gz |
Detect local "primary" IP address
Diffstat (limited to 'lib/pure/net.nim')
-rw-r--r-- | lib/pure/net.nim | 20 |
1 files changed, 20 insertions, 0 deletions
diff --git a/lib/pure/net.nim b/lib/pure/net.nim index f468e1c5d..f55d5d900 100644 --- a/lib/pure/net.nim +++ b/lib/pure/net.nim @@ -1662,3 +1662,23 @@ proc connect*(socket: Socket, address: string, port = Port(0), socket.fd.setBlocking(true) doAssert socket.gotHandshake() socket.fd.setBlocking(true) + +proc getPrimaryIPAddr*(dest = parseIpAddress("8.8.8.8")): IpAddress = + ## Finds the local IP address, usually assigned to eth0 on LAN or wlan0 on WiFi, + ## used to reach an external address. Useful to run local services. + ## + ## No traffic is sent. + ## + ## Supports IPv4 and v6. + ## Raises OSError if external networking is not set up. + ## + ## .. code-block:: Nim + ## echo $getPrimaryIPAddr() # "192.168.1.2" + + let socket = + if dest.family == IpAddressFamily.IPv4: + newSocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP) + else: + newSocket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP) + socket.connect($dest, 80.Port) + socket.getLocalAddr()[0].parseIpAddress() |