[英]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.