Swift 4 域名解析 DNS(真机实测)

/ Mac / 没有评论 / 1404浏览

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
  }

}