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

查看:19
本文介绍了如何在 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.

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天全站免登陆