【问题标题】:How do I get the IP address of a local hostname in local network in Swift如何在 Swift 中获取本地网络中本地主机名的 IP 地址
【发布时间】:2015-11-18 06:54:14
【问题描述】:

如何快速获取本地网络上本地主机名(例如“myComputer”)的 IP 地址(例如 192.168.0.1)?

我试过这个:

let host = CFHostCreateWithName(nil,"www.google.com").takeRetainedValue();
CFHostStartInfoResolution(host, .Addresses, nil);
var success: Boolean = 0;
let addresses = CFHostGetAddressing(host, &success).takeUnretainedValue() 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) {
                println(numAddress)
            }
    }
} 

这适用于“www.google.com”之类的地址,但不适用于“myComputer”之类的主机名

我在 Xcode Simulator 中尝试过。它在那里工作,但在我的 iPhone 上不行

我会得到错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

...在第 4 行。

感谢您的帮助!

【问题讨论】:

    标签: ios swift networking


    【解决方案1】:

    myComputer 等本地主机名只有在您的 iPhone 的 DNS 服务器配置为解析它们(或它们在 hosts 文件中)时才可用于您的 iPhone。

    要在您的 iPhone 上解析 myComputer,您需要将您的 iPhone 配置为使用本地 DNS 服务器,该服务器将为您本地网络上的机器的主机名提供 IP 地址。

    您看到的错误与未获得结果有关。您需要检查主机是否已解析(CFHostStartInfoResolution 为此提供了结果):

    let host = CFHostCreateWithName(nil,"www.google.com").takeRetainedValue();
    var success : Boolean = CFHostStartInfoResolution(host, .Addresses, nil);
    if success > 0 {
        success = 0;
        let addresses = CFHostGetAddressing(host, &success).takeUnretainedValue() 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) {
                    println(numAddress)
                }
            }
        }
    } else {
        println("Host not found!")
    }
    

    【讨论】:

    • 所以你的意思是这样的?让地址:NSArray?地址 = CFHostGetAddressing(host, &success).takeUnretainedValue() as NSArray;如果地址 == nil { return "" } - 也不起作用
    • 查看我的更新答案以获得完整的解决方案,您看到的错误实际上发生在您收到来自 CFHostGetAddressing 的回复之前。
    猜你喜欢
    • 2010-09-17
    • 2012-04-12
    • 1970-01-01
    • 1970-01-01
    • 2012-10-28
    • 2014-06-01
    • 2017-02-21
    • 2014-06-09
    • 2015-07-02
    相关资源
    最近更新 更多