使用IP地址的可达性不起作用。

时间:2012-08-29 11:25:37

标签: iphone xcode ip-address reachability

输入Apple提供的Rechability类。 输入此内容后,Reachability reachabilityWithAddress:(const struct sockaddr_in *)hostAddress。我们应该如何输入我们要检查的IP地址到这一行? 这是我真正迷失的部分。

2 个答案:

答案 0 :(得分:2)

struct sockaddr_in是BSD套接字使用的低级“套接字地址”类型。我们通常不会在Cocoa级别处理它们,但它们可能会不时出现,包括在Apple的演示类中。这是因为SCNetworkReachability在其中一个创建函数中使用struct sockaddr_in

但幸运的是,您可以使用+reachabilityWithHostName:方法提供字符串,其中包括IP地址(与主机名一样,将由底层网络API自动解析。)

Reachability *r = [Reachability reachabilityWithHostName:@"1.2.3.4"];

答案 1 :(得分:0)

请尝试以下方法:

if ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] == NotReachable) {
        // do somehting meaningful!
}

或更具体:

Reachability* reachability = [Reachability sharedReachability];
[reachability setHostName:@"www.google.com"]; // set your host name/ip here
NetworkStatus remoteHostStatus = [reachability remoteHostStatus];

if (remoteHostStatus == NotReachable) { NSLog(@"no"); }
else if (remoteHostStatus == ReachableViaWiFiNetwork) { NSLog(@"wifi"); }
else if (remoteHostStatus == ReachableViaCarrierDataNetwork) { NSLog(@"cellular"); }