spatie/ping
Composer 安装命令:
composer require spatie/ping
包简介
Run an ICMP ping and get structured results
README 文档
README
This package provides a simple way to execute ICMP ping commands and parse the results into structured data. It wraps the system's ping command and returns detailed information about packet loss, response times, and connectivity status.
use Spatie\Ping\Ping; $result = (new Ping('8.8.8.8'))->run(); // returns an instance of \Spatie\Ping\PingResult // Basic status echo $result->isSuccess() ? 'Success' : 'Failed'; echo $result->hasError() ? "Error: {$result->error()?->value}" : 'No errors'; // Packet statistics echo "Packets transmitted: {$result->packetsTransmitted()}"; echo "Packets received: {$result->packetsReceived()}"; echo "Packet loss: {$result->packetLossPercentage()}%"; // Timing information echo "Min time: {$result->minimumTimeInMs()}ms"; echo "Max time: {$result->maximumTimeInMs()}ms"; echo "Average time: {$result->averageTimeInMs()}ms"; echo "Standard deviation: {$result->standardDeviationTimeInMs()}ms"; // Individual ping lines foreach ($result->lines() as $line) { echo "Response: {$line->getRawLine()} ({$line->getTimeInMs()}ms)"; }
Support us
We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.
We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.
Installation
You can install the package via Composer:
composer require spatie/ping
Usage
The simplest way to ping a host:
use Spatie\Ping\Ping; $result = (new Ping('8.8.8.8'))->run(); if ($result->isSuccess()) { echo "Ping successful! Average response time: {$result->averageResponseTimeInMs()}ms"; } else { echo "Ping failed: {$result->error()?->value}"; }
Configuring ping options
You can customize the ping behavior using constructor parameters:
$result = (new Ping( hostname: '8.8.8.8', timeoutInSeconds: 5, // seconds count: 3, // number of packets intervalInSeconds: 1.0, // seconds between packets packetSizeInBytes: 64, // how big the packet is we'll send to the server ttl: 64, // time to live (maximum number of hops) showLostPackets: true // report outstanding replies (Linux only, enabled by default) ))->run();
Or use the fluent interface:
$result = (new Ping('8.8.8.8')) ->timeoutInSeconds(10) ->count(5) ->intervalInSeconds(0.5) ->packetSizeInBytes(128) ->ttl(32) ->showLostPackets(false) ->run();
IPv4 and IPv6 support
By default, pings use IPv4. You can change this using the ipVersion option:
use Spatie\Ping\Enums\IpVersion; // IPv4 (default) $result = (new Ping('google.com'))->run(); // Force IPv6 $result = (new Ping('google.com')) ->ipVersion(IpVersion::IPv6) ->run(); // Auto-detect based on hostname $result = (new Ping('google.com')) ->ipVersion(IpVersion::Auto) ->run();
You can also set the IP version in the constructor:
use Spatie\Ping\Enums\IpVersion; $result = (new Ping('google.com', ipVersion: IpVersion::IPv4))->run();
The IP version used is included in the result:
$result = (new Ping('google.com'))->run(); echo $result->ipVersion()->value; // 'ipv4'
Lost packet reporting
The showLostPackets option enables the -O flag on Linux systems, which reports outstanding ICMP ECHO replies before sending the next packet. This is useful for diagnostic purposes and logging when investigating network connectivity issues:
// Enabled by default on Linux (ignored on macOS) $result = (new Ping('8.8.8.8'))->run(); // Explicitly disable $result = (new Ping('8.8.8.8')) ->showLostPackets(false) ->run(); // Explicitly enable $result = (new Ping('8.8.8.8')) ->showLostPackets(true) ->run();
Output example
With showLostPackets: true (default), the raw output will include notifications about missing replies:
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=117 time=15.2 ms
no answer yet for icmp_seq=2
64 bytes from 8.8.8.8: icmp_seq=3 ttl=117 time=12.8 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=117 time=45.1 ms
--- 8.8.8.8 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss
With showLostPackets: false, only successful replies are shown:
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=117 time=15.2 ms
64 bytes from 8.8.8.8: icmp_seq=3 ttl=117 time=12.8 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=117 time=45.1 ms
--- 8.8.8.8 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss
Note: This option only works on Linux systems and is automatically ignored on macOS.
Working with results
The PingResult object provides detailed information about the ping operation:
$result = (new Ping('8.8.8.8', count: 3))->run(); // Basic status echo $result->isSuccess() ? 'Success' : 'Failed'; echo $result->hasError() ? "Error: {$result->error()?->value}" : 'No errors'; // Packet statistics echo "Packets transmitted: {$result->packetsTransmitted()}"; echo "Packets received: {$result->packetsReceived()}"; echo "Packet loss: {$result->packetLossPercentage()}%"; // Timing information echo "Min time: {$result->minimumTimeInMs()}ms"; echo "Max time: {$result->maximumTimeInMs()}ms"; echo "Average time: {$result->averageTimeInMs()}ms"; echo "Standard deviation: {$result->standardDeviationTimeInMs()}ms"; // Individual ping lines foreach ($result->lines() as $line) { echo "Response: {$line->getRawLine()} ({$line->getTimeInMs()}ms)"; } // Raw ping output echo $result->raw;
Converting to array
You can convert the result to an array for easy serialization:
$result = (new Ping('8.8.8.8'))->run(); $array = $result->toArray(); // The array contains all ping data: // [ // 'success' => true, // 'error' => null, // 'host' => '8.8.8.8', // 'packet_loss_percentage' => 0, // 'packets_transmitted' => 4, // 'packets_received' => 4, // 'options' => [ // 'timeout_in_seconds' => 5, // 'interval' => 1.0, // 'packet_size_in_bytes' => 56, // 'ttl' => 64, // ], // 'timings' => [ // 'minimum_time_in_ms' => 8.5, // 'maximum_time_in_ms' => 12.3, // 'average_time_in_ms' => 10.2, // 'standard_deviation_time_in_ms' => 1.8, // ], // 'raw_output' => '...', // 'lines' => [...], // ]
You can also reconstruct a PingResult from an array:
$newResult = PingResult::fromArray($array);
Error handling
The error() method on a PingResult will return a case of the Spatie\Ping\Enums\PingError enum.
use Spatie\Ping\Ping; $result = (new Ping('non-existent-host.invalid'))->run(); if (! $result->isSuccess()) { return $result->error() // returns the enum case Spatie\Ping\Enums\PingError::HostnameNotFound }
Testing
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Credits
License
The MIT License (MIT). Please see License File for more information.
spatie/ping 适用场景与选型建议
spatie/ping 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 49.08k 次下载、GitHub Stars 达 91, 最近一次更新时间为 2025 年 07 月 02 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「ping」 「spatie」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 spatie/ping 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 spatie/ping 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 spatie/ping 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Ping uses the ICMP protocol's mandatory ECHO_REQUEST datagram to elicit an ICMP ECHO_RESPONSE from a host or gateway.
Receive webhooks in Laravel apps
Ping for Laravel.
Native ping command without any dependencies. Through ICMP protocol.
Easily optimize images using PHP
Store your application settings
统计信息
- 总下载量: 49.08k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 91
- 点击次数: 25
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-07-02