-
-
Save Erica-Iris/a0f95c31a0a6a4cb6c3a2584fb1c68ea 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