在Objective C中测试IP地址的连接性/可用性

时间:2016-04-21 21:17:48

标签: ios objective-c

基本上我希望能够检查本地网络上的特定主机是否“正常运行”。

当主机无法访问时,以下代码行会挂起,所以我想在运行之前先执行检查。

    [_outputStream write:[data bytes] maxLength:[data length]];

我认为类似的查询会在以下链接中得到解答,但我认为我需要使用CFHostCreateWithAddress而不是CFHostCreateWithName

Alternatives to NSHost in iPhone app

这是我尝试做的事情......

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");
}

2 个答案:

答案 0 :(得分:1)

将可达性类添加到项目中。

 #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

答案 1 :(得分:0)

看看Tony Million的Reachability课程: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。