rjstelling rjstelling - 6 months ago 171
Objective-C Question

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.

Answer

The code below seems to be working synchronously:

const char *hostName = [@"stackoverflow.com"
                        cStringUsingEncoding:NSASCIIStringEncoding];
SCNetworkConnectionFlags flags = 0;
if (SCNetworkCheckReachabilityByName(hostName, &flags) && flags > 0) {
  NSLog(@"Host is reachable: %d", flags);
}
else {
  NSLog(@"Host is unreachable");
}

Note: SystemConfiguration.framework is required

Comments