purplepixie/php-ping

PHP ICMP/Ping 网络客户端

1.01.0 2023-11-07 18:04 UTC

This package is auto-updated.

Last update: 2024-09-07 20:07:26 UTC


README

PPPing,Purplepixie PHP Ping 库是一个基于低级套接字的 ICMP ping 库,由 David Cutting 编写,用于 FreeNATS 网络监控器,但现在已作为一个独立的库分离出来。

获取 PPPing

最简单的方法是使用 composer 通过以下命令从 Packagist 获取最新包:

composer require purplepixie/php-ping

使用 composer,您可以根据需要自动加载类。

您也可以直接下载源代码(从标记的版本或克隆仓库)并包含文件 src/PurplePixie/PhpPing/PPPing.php

注意 PPPing 类在命名空间 \PurplePixie\PhpPing\PPPing 中。

使用 PPPing

一旦包含,使用 PPPing 就非常简单。

use \PurplePixie\PhpPing\PPPing;
$ping = new PPPing(); // instantiate a PPPing object
$ping->setHostname("www.google.com"); // host to ping (hostname or IP)
$result=$ping->Ping(); // perform a single ICMP ping
// Result is either a negative number (error) or 0 up which is return in ms
if ($result<0) // error
    echo "Error: ".$ping->strError($result)."\n";
else
    echo "Return: ".$result." ms\n";

其他可用信息

在 ping 信息之后,可以通过 PPPing::getLast() 获取最后结果的详细信息,它是一个键值对的关联数组,键如下所示

  • set - boolean 表示是否返回数据
  • result - ping 的结果值(负数表示错误,0 或正数表示返回时间,单位为 ms)
  • ttl - 返回数据包的 TTL
  • hops - 根据套接字 TTL 和返回 TTL 的跳数估计(不一定准确)
  • source - 返回数据包源的 IP 地址(远程系统)
  • destination - 返回数据包目的地的 IP 地址(本地系统)

其他选项和变量

可以在 PPPing 对象中读取和设置各种选项

  • PPPing::getHostname() 获取远程主机名或 IP
  • PPPing::setHostname($host) 设置远程主机名或 IP
  • PPPing::getTTL() 获取 TTL
  • PPPing::setTTL($ttl) 设置 TTL
  • PPPing::getTimeout() 获取超时时间(秒)
  • PPPing::setTimeout($timeout) 设置超时时间(秒)
  • PPPing::getPackage() 获取数据包包名(默认为 "PPPing")
  • PPPing::setPackage($package) 设置数据包包名
  • PPPing::getDebug() 获取调试状态标志(布尔值)
  • PPPing::setDebug($d) 设置调试状态标志(布尔值)
  • PPPing::getSequence() 获取序列号
  • PPPing::setSequence($s) 设置序列号
  • PPPing::getIdentity() 获取使用的标识符
  • PPPing::getLast() 获取最后一个 ping 的数据

示例 CLI 实现

bin 文件夹中有一个 ping.php,可以在命令行上运行以演示 PPPing 的功能。ping.php 脚本的选项包括:

Usage: php ping.php [options] hostname

Options available are as follows:

 --ttl x | -t x    Set TTL (not working with ppping yet)
 --debug | -d      Turn on debug mode and output
 --delay x         Minimum delay between pings in seconds (or decimal)
 --help | -h       Display this help and quit
 --count x | -c x  Number of times to ping (default infinity)

hostname must be a resolvable host or an IP address to ping (required)