1. 程式人生 > >Swift 4 域名解析 DNS(真機實測)

Swift 4 域名解析 DNS(真機實測)

引用於GitHub:https://github.com/xiaoxiaocainiao/HostToIP/blob/master/HostToIP/ViewController.swift
這裡又根據自己需要做了少許改動,在此感謝下作者的無私提供。

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        getIPAddress("www.baidu.com")
    }

    override
func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // 域名解析 func getIPAddress(domainName: String) -> String { var result = "" let host = CFHostCreateWithName(nil,domainName as CFString).takeRetainedValue() CFHostStartInfoResolution(host, .addresses, nil) var
success: DarwinBoolean = false if let addresses = CFHostGetAddressing(host, &success)?.takeUnretainedValue() as NSArray?, let theAddress = addresses.firstObject as? NSData { 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) result = numAddress print(numAddress) } } return result } }