Search code examples
iosobjective-csocketsreachability

iOS reachability for socket connection


I need to check for reachability for a socket connection in my application. I have gone through apple's sample code and few examples I could find from SO and other websites but I'm out of luck as I do not get any response. Here's a sample code I'm trying.

My requirement is simply to verify connectivity to myhost:port which is a socket connection. myhost is an address from dyndns.org

struct sockaddr_in server_address;
    server_address.sin_len = sizeof(server_address);
    server_address.sin_family = AF_INET;
    server_address.sin_port = htons(1234);
    server_address.sin_addr.s_addr = inet_addr("host-from-dyndns.org");

    Reachability *reachability = [Reachability reachabilityWithAddress:&server_address];

    __weak Reachability *weakReachability = reachability;
    reachability.reachableBlock = ^(Reachability*reach)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"REACHABLE!");
        });
        [weakReachability stopNotifier];
    };

    reachability.unreachableBlock = ^(Reachability*reach)
    {
        NSLog(@"UNREACHABLE!");
        [weakReachability stopNotifier];
    };

    [reachability startNotifier];

Solution

  • After few failed attempts of meddling with with reachability classes, I gave up and used a temporary asynchronous socket connection created on demand to verify the connection. It works as expected and is built on top of gcd. Also I found the AsyncSocket by Robbie Hanson (https://github.com/robbiehanson/CocoaAsyncSocket) to be quite helpful while implementing for my requirement.