21zach2
21zach2

Reputation: 159

Reachability with Address - Server AND Port - iOS 5

I am trying to check whether a server is online or offline: I face the problem that it has a port when connecting to it

My code at the moment:

struct sockaddr_in address;
address.sin_len = sizeof(address);
address.sin_family = AF_INET;
address.sin_port = htons(25667);
address.sin_addr.s_addr = inet_addr("fr7.mooshroom.net");

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

Please let me know what im doing wrong. And please dont link me to other questions, I have searched and none of them have what I'm looking for.

Upvotes: 4

Views: 3240

Answers (2)

21zach2
21zach2

Reputation: 159

I have fixed it now, i needed to put the line:
const char *serverIPChar = [serverIP cStringUsingEncoding:NSASCIIStringEncoding];
and replace the "fr7.mooshroom.net" inside the inet_addr to serverIPChar. Thanks anyway

Upvotes: 1

ChrisH
ChrisH

Reputation: 924

Basically the inet_addr() function does not do domain name resolution for you. You need to pass it an IP address (for example 127.0.0.1).

To resolve a DNS name into an IP address you need to look at the standard gethostbyname() functions.

To clarify:

struct hostent *host = gethostbyname("fr7.mooshroom.net");
if (host) {
    struct in_addr in;
    NSLog(@"HOST: %s" , host->h_name);
    while (*host->h_addr_list)
    {
        bcopy(*host->h_addr_list++, (char *) &in, sizeof(in));
        NSLog(@"IP: %s", inet_ntoa(in));
    }
}

Now, having said all that, are you sure this is going to do what you want? Documentation for SCNetworkReachabilityRef suggests not:

http://developer.apple.com/library/ios/#documentation/SystemConfiguration/Reference/SCNetworkReachabilityRef/Reference/reference.html

"A remote host is considered reachable when a data packet, sent by an application into the network stack, can leave the local device. Reachability does not guarantee that the data packet will actually be received by the host."

Upvotes: 5

Related Questions