使用PHP检查主机是否在线?
我的互联网连接遇到了一些问题,我想知道检查主机是否连接到互联网的最快、无错误和最可靠的方法是什么。
我正在寻找类似 is_online()
的东西,在线时返回 true,离线时返回 false。
I've been having some issues with my Internet connection and I was wondering what is the fastest, error-less and most reliable way to check if the host computer is connected to the Internet.
I'm looking for something like is_online()
that returns true when online and false when not.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我对一些解决方案进行了基准测试: file_get_contents 与 HEAD 请求, gethostbynamel, checkdnsrr 和以下解决方案似乎比所有其他解决方案快 100 倍以上:
每个主机大约需要一微秒,而 <例如,每个主机的 code>file_get_contents 花费的时间超过一秒(离线时)。
I've benchmarked some solutions: file_get_contents with HEAD request, gethostbynamel, checkdnsrr and the following solution seems to be more than 100 faster than all the others:
Takes about one microsecond per each host, while
file_get_contents
for instance takes more than one second per each host (when offline).您可以向可能已启动的主机(例如 Google)发送 ping。
似乎没有为此内置 PHP,因此您必须求助于 shell 命令。 *nix 上
ping
的返回值可以告诉您是否收到回复。更新:
ping -c1 -q -w1
应该是 Linux 上的正确命令。如果收到回复,则返回退出代码 0,否则返回退出代码,一秒后超时。因此,像这样的东西(警告,我的 PHP 生锈了)应该可以解决问题:
You could send a ping to a host that is probably up (e.g. Google).
There seems to be no PHP built-in for this, so you'd have to resort to shell commands. The return value of
ping
on *nix can tell you whether a reply was received.Update:
ping -c1 -q -w1
should be the right command on Linux. This will give you exit code 0 if a reply was received, something else otherwise, and it times out after one second.Hence, something like this (warning, my PHP is rusty) should do the trick:
为什么不在流行网站上执行多个
HTTP GET
(或者更好的HTTP HEAD
以提高速度)请求?使用多数投票来决定答案。有时您也可以依赖
ping
(通过 PHP 中的系统调用),但请注意,并非所有网站都会响应 ICMP (ping) 请求。注意,在得出结论之前增加 ping/http 请求的数量有助于提高答案的置信度,但不能在最坏的情况下也不会出现错误。
Why don't you do a number of
HTTP GET
(or better stillHTTP HEAD
for speed) requests on popular web sites? Use majority voting to decide on the answer.You can sometimes rely on
ping
too (through a system call in PHP) but note that not all web sites respond to ICMP (ping) requests.Note that by increasing the number of ping/http requests you make before drawing a conclusion helps with the confidence level of the answer but can't be error free in the worst of cases.
不要忘记这假设您的服务器将响应 ICMP 请求。如果是这样的话,那么我同意,Net_Ping 可能是最佳选择。如果失败,您可以使用 PEAR 上的 Net_Socket 包来尝试连接到某个您知道会收到响应的端口 - 可能是端口 7 或端口 80,具体取决于您运行的服务。
Don't forget this assumes that your server will respond to ICMP requests. If that's the case then I agree, Net_Ping is probably the way to go. Failing that you could use the Net_Socket package, also on PEAR, to attempt a connection to some port that you know will get a response from - perhaps port 7 or port 80 depending on what services you have running.