DNSResolver: getaddrinfo returns a sockaddr and inet_ntop takes strlen

The way this was written before was totally wrong.

Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
This commit is contained in:
Jason A. Donenfeld 2018-11-02 05:34:17 +01:00
parent 6676e557f1
commit 7fc0e3ee94
1 changed files with 6 additions and 4 deletions

View File

@ -111,18 +111,20 @@ extension DNSResolver {
while (resultPointer != nil) { while (resultPointer != nil) {
let result = resultPointer!.pointee let result = resultPointer!.pointee
resultPointer = result.ai_next resultPointer = result.ai_next
if (result.ai_family == AF_INET && result.ai_addrlen == INET_ADDRSTRLEN) { if (result.ai_family == AF_INET && result.ai_addrlen == MemoryLayout<sockaddr_in>.size) {
if (inet_ntop(result.ai_family, result.ai_addr, ipv4Buffer, result.ai_addrlen) != nil) { var sa4 = UnsafeRawPointer(result.ai_addr)!.assumingMemoryBound(to: sockaddr_in.self).pointee
if (inet_ntop(result.ai_family, &sa4.sin_addr, ipv4Buffer, socklen_t(INET_ADDRSTRLEN)) != nil) {
ipv4AddressString = String(cString: ipv4Buffer) ipv4AddressString = String(cString: ipv4Buffer)
// If we found an IPv4 address, we can stop // If we found an IPv4 address, we can stop
break break
} }
} else if (result.ai_family == AF_INET6 && result.ai_addrlen == INET6_ADDRSTRLEN) { } else if (result.ai_family == AF_INET6 && result.ai_addrlen == MemoryLayout<sockaddr_in6>.size) {
if (ipv6AddressString != nil) { if (ipv6AddressString != nil) {
// If we already have an IPv6 address, we can skip this one // If we already have an IPv6 address, we can skip this one
continue continue
} }
if (inet_ntop(result.ai_family, result.ai_addr, ipv6Buffer, result.ai_addrlen) != nil) { var sa6 = UnsafeRawPointer(result.ai_addr)!.assumingMemoryBound(to: sockaddr_in6.self).pointee
if (inet_ntop(result.ai_family, &sa6.sin6_addr, ipv6Buffer, socklen_t(INET6_ADDRSTRLEN)) != nil) {
ipv6AddressString = String(cString: ipv6Buffer) ipv6AddressString = String(cString: ipv6Buffer)
} }
} }