在Objective C编程中,reachabilityWithAddress不起作用

我想检查一个服务器是否带有ip,例如74.125.71.104(Google的ip)

//分配一个可达性对象

`struct sockaddr_in address; address.sin_len = sizeof(address); address.sin_family = AF_INET; address.sin_port = htons(80); address.sin_addr.s_addr = inet_addr("74.125.71.104");` Reachability *reach = [Reachability reachabilityWithAddress:&address]; 

但那些不工作。

当我改变到reachabilityWithHostname ,它的工作。

请导入#include <arpa/inet.h>

  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil]; struct sockaddr_in address; address.sin_len = sizeof(address); address.sin_family = AF_INET; address.sin_port = htons(8080); address.sin_addr.s_addr = inet_addr("216.58.199.174"); //google ip self.internetReachability = [Reachability reachabilityWithAddress:&address]; [self.internetReachability startNotifier]; [self updateInterfaceWithReachability:self.internetReachability]; 

编辑

根据你的评论,你的可达性块不会被调用。 我总是使用不太了解可达性块的通知。 所以我更喜欢使用通知如下。

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil]; struct sockaddr_in address; address.sin_len = sizeof(address); address.sin_family = AF_INET; address.sin_port = htons(8080); address.sin_addr.s_addr = inet_addr("216.58.199.174"); self.internetReachability = [Reachability reachabilityWithAddress:&address]; [self.internetReachability startNotifier]; [self updateInterfaceWithReachability:self.internetReachability]; 

现在,只要你的互联网状态改变reachabilityChanged方法将触发与可达性实例:)

 - (void) reachabilityChanged:(NSNotification *)note { Reachability* curReach = [note object]; [self updateInterfaceWithReachability:curReach]; } 

最后实现updateInterfaceWithReachability

 - (void)updateInterfaceWithReachability:(Reachability *)reachability { NetworkStatus netStatus = [reachability currentReachabilityStatus]; switch (netStatus) { case NotReachable: { //not reachable } break; case ReachableViaWWAN: case ReachableViaWiFi: { //reachable via either 3g or wifi } break; } } 

希望这可以帮助。