29 lines
987 B
Nim
29 lines
987 B
Nim
from net import
|
|
IpAddress, IpAddressFamily, Port, newSocket, connect, close, getLocalAddr,
|
|
parseIpAddress
|
|
from nativesockets import
|
|
AF_INET, AF_INET6, SOCK_DGRAM, IPPROTO_UDP
|
|
|
|
# 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)
|
|
socket.connect($dest, 80.Port)
|
|
result = socket.getLocalAddr()[0].parseIpAddress()
|
|
socket.close()
|