Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
432 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...