Reachability with Address - Server AND Port - iOS 5

巧了我就是萌 提交于 2019-12-23 15:19:22

问题


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.


回答1:


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."




回答2:


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



来源:https://stackoverflow.com/questions/11395397/reachability-with-address-server-and-port-ios-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!