从iOS上的主机名解析和IP地址,可以使用以下方法:
DNS
协议进行主机名解析:DNS
是一种将主机名转换为IP地址的协议。在iOS上,可以使用DNS
协议进行主机名解析。以下是一个使用DNS
协议进行主机名解析的示例代码:
import Foundation
let hostname = "www.example.com"
let dnsResolver = CFHostCreateWithName(kCFAllocatorDefault, hostname as CFString).takeRetainedValue()
CFHostStartInfoResolution(dnsResolver, .addresses, nil)
var success: DarwinBoolean = false
if let addresses = CFHostGetAddressing(dnsResolver, &success)?.takeUnretainedValue() as? [Data] {
for address in addresses {
let ipAddress = address.withUnsafeBytes { pointer in
pointer.bindMemory(to: Int8.self).map { String(cString: $0) }
}
print("IP address: \(ipAddress)")
}
}
URLSession
进行网络请求:URLSession
是一种进行网络请求的方法。在iOS上,可以使用URLSession
进行网络请求。以下是一个使用URLSession
进行网络请求的示例代码:
import Foundation
let url = URL(string: "https://www.example.com")!
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
print("Error: \(error.localizedDescription)")
return
}
guard let httpResponse = response as? HTTPURLResponse else {
print("Error: Invalid response")
return
}
let statusCode = httpResponse.statusCode
print("Status code: \(statusCode)")
if let data = data {
let string = String(data: data, encoding: .utf8)
print("Response: \(string)")
}
}
task.resume()
以上是两种在iOS上进行主机名解析和IP地址的方法。
领取专属 10元无门槛券
手把手带您无忧上云