2020-10-10 11:48:56 +02:00
|
|
|
from net import
|
2020-10-10 11:57:52 +02:00
|
|
|
IpAddress, IpAddressFamily, Port, `$`, newSocket, connect, close,
|
|
|
|
getLocalAddr, parseIpAddress
|
2020-10-10 11:48:56 +02:00
|
|
|
from nativesockets import
|
2020-10-10 11:57:52 +02:00
|
|
|
Domain, SockType, Protocol
|
2020-10-10 11:48:56 +02:00
|
|
|
|
|
|
|
# FIXME: getPrimaryAddr is not needed anymore once
|
|
|
|
# https://github.com/nim-lang/Nim/pull/15538 is released.
|
|
|
|
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)
|
2020-10-12 21:32:43 +02:00
|
|
|
try:
|
|
|
|
socket.connect($dest, 80.Port)
|
|
|
|
result = socket.getLocalAddr()[0].parseIpAddress()
|
|
|
|
finally:
|
|
|
|
socket.close()
|