From 0c1520d6f8b84b8f9fb8191b3e6a0cd03966869f Mon Sep 17 00:00:00 2001 From: Jeroen Leenarts Date: Sun, 30 Sep 2018 21:39:00 +0200 Subject: [PATCH] Convert DNS names to IP address. Signed-off-by: Jason A. Donenfeld --- Shared/Validators.swift | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/Shared/Validators.swift b/Shared/Validators.swift index 4eb19cb..21758fe 100644 --- a/Shared/Validators.swift +++ b/Shared/Validators.swift @@ -31,12 +31,12 @@ struct Endpoint { var addressType: AddressType init?(endpointString: String, needsPort: Bool = true) throws { - var ipString: String + var hostString: String if needsPort { guard let range = endpointString.range(of: ":", options: .backwards, range: nil, locale: nil) else { throw EndpointValidationError.noIpAndPort(endpointString) } - ipString = String(endpointString[.. String { + let host = CFHostCreateWithName(nil, hostname as CFString).takeRetainedValue() + CFHostStartInfoResolution(host, .addresses, nil) + var success: DarwinBoolean = false + if let addresses = CFHostGetAddressing(host, &success)?.takeUnretainedValue() as NSArray?, + let theAddress = addresses.firstObject as? NSData { + var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST)) + if getnameinfo(theAddress.bytes.assumingMemoryBound(to: sockaddr.self), socklen_t(theAddress.length), + &hostname, socklen_t(hostname.count), nil, 0, NI_NUMERICHOST) == 0 { + let numAddress = String(cString: hostname) + return numAddress + } + } + return hostname +} + func validateIpAddress(ipToValidate: String) -> AddressType { var sin = sockaddr_in()