Skip to content

Instantly share code, notes, and snippets.

@koleto
Forked from stropdale/dnsLookup.swift
Created April 24, 2024 15:47
Show Gist options
  • Save koleto/27e505a0ac0ae0ad32bc49d87e22ac95 to your computer and use it in GitHub Desktop.
Save koleto/27e505a0ac0ae0ad32bc49d87e22ac95 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"))
@koleto
Copy link
Author

koleto commented Apr 24, 2024

func getIP4s(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 theAddress.length == MemoryLayout<sockaddr_in>.stride { // Check if it's an IPv4 address
                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
}

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