代码如下:
func dnsToIP() -> String? {
let host = CFHostCreateWithName(nil, "baidu.com").takeRetainedValue()
CFHostStartInfoResolution(host, .Addresses, nil)
var success: Boolean = 0
if let addressesCF = CFHostGetAddressing(host, &success) {
let addresses = addressesCF.takeRetainedValue() as NSArray
if addresses.count != 0 {
let theAddress = addresses[0] as! NSData
var hostname = [CChar](count: Int(NI_MAXHOST), repeatedValue: 0)
if getnameinfo(UnsafePointer(theAddress.bytes), socklen_t(theAddress.length), &hostname, socklen_t(hostname.count), nil, 0, NI_NUMERICHOST) == 0 {
if let numAddress = String.fromCString(hostname) {
return numAddress
}
}
}
} else {
NSLog("域名出错")
}
return nil
}
上述代码有些许漏洞,正在修正中,目前可使用Swift中利用域名获得IP地址 C方式
借鉴信息:
http://stackoverflow.com/questions/25890533/how-can-i-get-a-real-ip-address-from-dns-query-in-swift