Skip to content

Instantly share code, notes, and snippets.

@Erica-Iris
Forked from stropdale/dnsLookup.swift
Created February 2, 2024 12:48
Show Gist options
  • Save Erica-Iris/a0f95c31a0a6a4cb6c3a2584fb1c68ea to your computer and use it in GitHub Desktop.
Save Erica-Iris/a0f95c31a0a6a4cb6c3a2584fb1c68ea 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"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment