Franky
Franky

Reputation: 912

reachability test for specific ip/port

I'm trying to check if an address and Port are available. For that I follow the different steps in this post (iphone) reachability test for specific ip/port? and my code :

BOOL hasLeadingNumberInString(NSString* s) {
    if (s)
        return [s length] && isnumber([s characterAtIndex:0]);
    else
        return NO;
}

-(BOOL)networkConnected: (NSString *)ipAdress Port:(int)port {
    SCNetworkReachabilityFlags  flags = 0;
    SCNetworkReachabilityRef    netReachability;
    BOOL                        retrievedFlags = NO;

    // added the "if" and first part of if statement
    //
    if (hasLeadingNumberInString(ipAdress)) {
        struct sockaddr_in the_addr;
        memset((void *)&the_addr, 0, sizeof(the_addr));
        the_addr.sin_family = AF_INET;
        the_addr.sin_port = htons(port);
        const char* server_addr = [ipAdress UTF8String];
        unsigned long ip_addr = inet_addr(server_addr);
        the_addr.sin_addr.s_addr = ip_addr;
        netReachability =    SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (struct sockaddr*)&the_addr);
    } else {
        netReachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [ipAdress UTF8String]);
    }
    if (netReachability) {
        retrievedFlags = SCNetworkReachabilityGetFlags(netReachability, &flags);
        CFRelease(netReachability);
    }
    if (!retrievedFlags || !flags) {
        return NO;
    }
    return YES;
}

But I always have NO even if couple address/port exist. What I'm doing wrong??

EDIT LOG:

netReachability is NIL

Upvotes: 0

Views: 2926

Answers (2)

borrrden
borrrden

Reputation: 33421

the_addr.sin_len = sizeof(the_addr);

You forgot to set this part of the struct. Without it, it will be interpreted as zero-length (invalid). If you set it, your SCNetworkReachabilityRef will no longer be NULL.

Upvotes: 3

Martin R
Martin R

Reputation: 539685

The SCNetworkReachabilityCreateWithAddress() fails because you forgot to set

the_addr.sin_len = sizeof(the_addr);

If you add that it should work.

But note that the SCNetworkReachability functions only check if a packet can be routed to the destination. It does not verify if a host is actually listening at the given port.

Therefore, the port number is irrelevant, and you could just use

netReachability  = SCNetworkReachabilityCreateWithName(NULL, server_addr);

without all the struct sockaddr_in hassle.

Upvotes: 2

Related Questions