基本上,我希望能够检查本地网络上的特定主机是否"启动"。
当无法访问主机时,以下代码行将挂起,因此我想在运行它之前先执行检查。
[_outputStream write:[data bytes] maxLength:[data length]];
我认为类似的查询在以下链接中得到了回答,但我认为我需要使用CFHostCreateWithAddress
而不是CFHostCreateWithName
iPhone应用程序中NSHost的替代品
这是我
尝试做的事情...Boolean result;
struct sockaddr_in address;
address.sin_family = AF_INET;
address.sin_port = htons(80);
inet_pton(AF_INET, "192.168.1.31", &address.sin_addr);
CFDataRef sockData = CFDataCreate(NULL, &address, sizeof(address));
CFHostRef host = CFHostCreateWithAddress(NULL, sockData);
result = CFHostStartInfoResolution(host, kCFHostAddresses, NULL);
if (result == TRUE) {
NSLog(@"Resolved");
} else {
NSLog(@"Not resolved");
}
即使主机启动,我也没有解决。
下面是我尝试使用 Reachability 类。我的代码告诉我,尽管指定地址没有主机,但以下地址是可访问的。
struct sockaddr_in address;
address.sin_family = AF_INET;
address.sin_port = htons(80);
inet_pton(AF_INET, "192.168.1.31", &address.sin_addr);
Reachability *reachability = [Reachability reachabilityWithAddress:&address];
NetworkStatus reachabilitytoHost = [reachability currentReachabilityStatus];
if(reachabilitytoHost != NotReachable)
{
NSLog(@"Reachable");
}
else
{
NSLog(@"Not Reachable");
}
可达性类添加到项目中。
#import "Reachability.h"
同时添加SystemConfiguration
框架。
Reachability *reachability = [Reachability reachabilityWithHostName:@"www.example.com"];
NetworkStatus reachabilitytoHost = [reachability currentReachabilityStatus];
if(reachabilitytoHost != NotReachable)
{
//reachable
}
else
{
// not reachable
}
在此处检查示例代码:https://developer.apple.com/library/ios/samplecode/Reachability/Introduction/Intro.html
欲了解更多信息: https://developer.apple.com/library/ios/samplecode/Reachability/Listings/Reachability_Reachability_h.html
看看 Tony Million: 的 Reachability class: https://github.com/tonymillion/Reachability
来自自述文件:
// Allocate a reachability object
Reachability* reach = [Reachability reachabilityWithHostname:@"www.google.com"];
// Set the blocks
reach.reachableBlock = ^(Reachability*reach)
{
// keep in mind this is called on a background thread
// and if you are updating the UI it needs to happen
// on the main thread, like this:
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"REACHABLE!");
});
};
reach.unreachableBlock = ^(Reachability*reach)
{
NSLog(@"UNREACHABLE!");
};
// Start the notifier, which will cause the reachability object to retain itself!
[reach startNotifier];
显然,您可以将 www.google.com 替换为要测试的任何地址。