Skip to content

Instantly share code, notes, and snippets.

@stropdale
Created July 29, 2019 15:28
Show Gist options
  • Save stropdale/7de7a1c25dcf9316b223d3364c60b168 to your computer and use it in GitHub Desktop.
Save stropdale/7de7a1c25dcf9316b223d3364c60b168 to your computer and use it in GitHub Desktop.
DNS IP Address Lookup from Host name in Swift
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"))
@MartinP7r
Copy link

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 to getIP depending on your use-case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment