【发布时间】: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