After inputting the Rechability classes Apple provided. Also after inputting this, Reachability reachabilityWithAddress:(const struct sockaddr_in *)hostAddress. How should we input the IP address we want to check into this line? This is the part where i'm really lost at.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
struct sockaddr_in
is a low-level "socket address" type used by BSD sockets. We generally don't deal with them at the Cocoa level, but they can creep up from time to time, including in Apple's demo class. The reason there is because SCNetworkReachability
uses a struct sockaddr_in
in one of its creation functions.
Fortunately for you, however, you can supply a string instead with the +reachabilityWithHostName:
method, and that includes IP addresses (which, like hostnames, will be resolved automatically for you by the underlying network APIs.)
Reachability *r = [Reachability reachabilityWithHostName:@"1.2.3.4"];
回答2:
Please try the following:
if ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] == NotReachable) {
// do somehting meaningful!
}
or to be more specific:
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"); }