Created
July 29, 2019 15:28
-
-
Save stropdale/7de7a1c25dcf9316b223d3364c60b168 to your computer and use it in GitHub Desktop.
DNS IP Address Lookup from Host name in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
// You many want to run this in the background | |
func getIPs(dnsName: String) -> String? { | |
let host = CFHostCreateWithName(nil, dnsName as CFString).takeRetainedValue() | |
CFHostStartInfoResolution(host, .addresses, nil) | |
var success: DarwinBoolean = false | |
if let addresses = CFHostGetAddressing(host, &success)?.takeUnretainedValue() as NSArray? { | |
for case let theAddress as NSData in addresses { | |
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 nil | |
} | |
print(getIPs(dnsName: "HostName")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice.
However, this is actually only returning one ip address, even if there's multiple.
You could return an array of addresses populated from the
numAddress
in line 14 or rename the function togetIP
depending on your use-case.