diff --git a/tcp_syni.nim b/tcp_syni.nim index 2a2937f..c5beea8 100644 --- a/tcp_syni.nim +++ b/tcp_syni.nim @@ -1,5 +1,5 @@ import asyncfutures, asyncdispatch, asyncnet, strformat -from net import IpAddress, Port, `$`, `==`, getPrimaryIPAddr, toSockAddr, parseIpAddress +from net import IpAddress, Port, `$`, `==`, toSockAddr, parseIpAddress from nativesockets import SockAddr, Sockaddr_storage, SockLen, setSockOptInt from random import randomize, rand from sequtils import any @@ -7,6 +7,7 @@ import asyncutils import ip_packet import network_interface import raw_socket +import utils var IPPROTO_IP {.importc: "IPPROTO_IP", header: "".}: cint var IP_TTL {.importc: "IP_TTL", header: "".}: cint diff --git a/utils.nim b/utils.nim new file mode 100644 index 0000000..1c74405 --- /dev/null +++ b/utils.nim @@ -0,0 +1,28 @@ +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()