如何在Cocoa / Objective-C中编写一个简单的Ping方法 [英] How to write a simple Ping method in Cocoa/Objective-C

查看:187
本文介绍了如何在Cocoa / Objective-C中编写一个简单的Ping方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Cocoa / Objective-C中编写一个简单的 ping 方法。它还需要在iPhone上工作。

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

我发现了一个使用 icmp 的示例, iPhone?

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

我倾向于使用 NSNetServices 的解决方案,这是个好主意吗?

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

该方法只需要 ping 几次并返回平均值,如果主机关闭或无法访问,则返回-1。 p>

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

推荐答案

下面的代码似乎是同步工作:

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

注意: SystemConfiguration.framework 是必需的

这篇关于如何在Cocoa / Objective-C中编写一个简单的Ping方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆