Add resolveTAddress(string, Port) and test for it.

This commit is contained in:
cheatfate 2018-06-07 01:15:31 +03:00
parent 3eb4a00397
commit a5be5303e3
2 changed files with 58 additions and 0 deletions

View File

@ -194,6 +194,31 @@ proc resolveTAddress*(address: string,
it = it.ai_next
freeAddrInfo(aiList)
proc resolveTAddress*(address: string, port: Port,
family = IpAddressFamily.IPv4): seq[TransportAddress] =
## Resolve string representation of ``address``.
##
## ``address`` could be dot IPv4/IPv6 address or hostname.
##
## If hostname address is detected, then network address translation via DNS
## will be performed.
var ta: TransportAddress
result = newSeq[TransportAddress]()
if isIpAddress(address):
ta = TransportAddress(address: parseIpAddress(address), port: port)
result.add(ta)
else:
var domain = if family == IpAddressFamily.IPv4: Domain(AF_INET) else:
Domain(AF_INET6)
var aiList = getAddrInfo(address, port, domain)
var it = aiList
while it != nil:
fromSockAddr(cast[ptr Sockaddr_storage](it.ai_addr)[],
SockLen(it.ai_addrlen), ta.address, ta.port)
result.add(ta)
it = it.ai_next
freeAddrInfo(aiList)
template checkClosed*(t: untyped) =
if (ReadClosed in (t).state) or (WriteClosed in (t).state):
raise newException(TransportError, "Transport is already closed!")

View File

@ -57,3 +57,36 @@ when isMainModule:
for item in hostnames:
var taseq = resolveTAddress(item)
check len(taseq) >= 1
test "resolveTAddress(string, Port)":
var numeric4 = [
"0.0.0.0",
"255.0.0.255",
"128.128.128.128",
"255.255.255.255"
]
var numeric6 = [
"::",
"ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
"aaaa:bbbb:cccc:dddd:eeee:ffff::1111",
"aaaa:bbbb:cccc:dddd:eeee:ffff::",
"a:b:c:d:e:f::",
"2222:3333:4444:5555:6666:7777:8888:9999"
]
var hostnames = [
"www.google.com",
"www.github.com"
]
for item in numeric4:
var taseq = resolveTAddress(item, Port(443))
check len(taseq) == 1
check $taseq[0] == item & ":443"
for item in numeric6:
var taseq = resolveTAddress(item, Port(443))
check len(taseq) == 1
check $taseq[0] == "[" & item & "]" & ":443"
for item in hostnames:
var taseq = resolveTAddress(item, Port(443))
check len(taseq) >= 1