【发布时间】:2012-08-23 23:57:16
【问题描述】:
输入 Apple 提供的 Rechability 类后。 同样在输入后,ReachabilityreachabilityWithAddress:(const struct sockaddr_in *)hostAddress。我们应该如何在这一行输入我们要检查的 IP 地址? 这是我真正迷失的部分。
【问题讨论】:
标签: iphone xcode ip-address reachability
输入 Apple 提供的 Rechability 类后。 同样在输入后,ReachabilityreachabilityWithAddress:(const struct sockaddr_in *)hostAddress。我们应该如何在这一行输入我们要检查的 IP 地址? 这是我真正迷失的部分。
【问题讨论】:
标签: iphone xcode ip-address reachability
struct sockaddr_in 是 BSD 套接字使用的低级“套接字地址”类型。我们通常不会在 Cocoa 级别处理它们,但它们会不时出现,包括在 Apple 的演示类中。原因是SCNetworkReachability 在其创建函数之一中使用了struct sockaddr_in。
不过,幸运的是,您可以使用 +reachabilityWithHostName: 方法提供一个字符串,其中包括 IP 地址(与主机名一样,底层网络 API 将自动为您解析。)
Reachability *r = [Reachability reachabilityWithHostName:@"1.2.3.4"];
【讨论】:
请尝试以下方法:
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"); }
【讨论】: