Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a simple Ping method in Cocoa/Objective-C

I need to write a simple ping method in Cocoa/Objective-C. It also needs to work on the iPhone.

I found an example that uses icmp, will this work on the iPhone?

I'm leaning towards a solution using NSNetServices, is this a good idea?

The method only needs to ping a few times and return the average and -1 if the host is down or unreachable.

like image 471
Richard Stelling Avatar asked Apr 28 '09 15:04

Richard Stelling


4 Answers

NOTE- I would recommend Chris' solution below which actually answers the question asked, directly. This post from 12 years ago was in response to the original authors upvoted answer, to which I had a better solution. As the author upvoted the answer above that used Reachability, I assumed that he was in fact more interested in reachability than actually in sending a ping, hence my answer. Please consider this before downvoting this answer.

StreamSCNetworkCheckReachabilityByName is deprecated and NOT available for the iPhone. Note: SystemConfiguration.framework is required

bool success = false;
const char *host_name = [@"stackoverflow.com" 
                         cStringUsingEncoding:NSASCIIStringEncoding];

SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL,
                                                                        host_name);
SCNetworkReachabilityFlags flags;
success = SCNetworkReachabilityGetFlags(reachability, &flags);

//prevents memory leak per Carlos Guzman's comment
CFRelease(reachability);

bool isAvailable = success && (flags & kSCNetworkFlagsReachable) && 
                             !(flags & kSCNetworkFlagsConnectionRequired);
if (isAvailable) {
    NSLog(@"Host is reachable: %d", flags);
}else{
    NSLog(@"Host is unreachable");
}
like image 65
Gene Myers Avatar answered Nov 20 '22 15:11

Gene Myers


I had this same problem, and ended up writing a simple wrapper around SimplePing to achieve this, wrote a blog about it and there's some code on github, hopefully will help someone here:

http://splinter.com.au/how-to-ping-a-server-in-objective-c-iphone

like image 21
Chris Avatar answered Nov 20 '22 14:11

Chris


You are not missing anything -- "Reachability" doesn't actually test that the target domain is in fact reachable, it only assesses if there is a pathway out of the machine by which the target domain is potentially reachable. So long as you have some outbound connection (e.g., an active wirless or wired connection), and a routing configuration that leads to the target, then the site is "reachable" as far as SCNetworkReachability is concerned.

like image 13
Zhami Avatar answered Nov 20 '22 15:11

Zhami


Pinging on the iPhone works a bit different than on other platforms, due to the fact that you don't have root access. See this sample code from Apple.

like image 5
Monobono Avatar answered Nov 20 '22 15:11

Monobono