[英]How do I get the IP address of a local hostname in local network in Swift
如何快速获取本地网络上本地主机名(例如“ 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行中
谢谢你的帮助!
如果将本地主机名(例如myComputer )配置为将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!")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.