reachabilityWithAddress is not working in Objectiv

2020-04-12 01:06发布

问题:

I want to check a server is live or not with ip, for example, 74.125.71.104 (Google's ip)

// allocate a reachability object

`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];

but those not working.

When I change to reachabilityWithHostname, it's working.

回答1:

Please import #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];

EDIT

As per your comments your reachability blocks are not called. I always use notifications not much aware of reachability blocks. So I prefer using notifications as follow.

[[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];

Now whenever your internet status changes reachabilityChanged method will be triggerred with reachability instance :)

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

Finally implement updateInterfaceWithReachability as

- (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;
            }
}

Hope this helps.