PHPackages                             spatie/ping - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Logging &amp; Monitoring](/categories/logging)
4. /
5. spatie/ping

ActiveLibrary[Logging &amp; Monitoring](/categories/logging)

spatie/ping
===========

Run an ICMP ping and get structured results

1.2.1(3mo ago)9031.9k↓14%9[1 PRs](https://github.com/spatie/ping/pulls)MITPHPPHP ^8.4CI passing

Since Jul 2Pushed 1mo agoCompare

[ Source](https://github.com/spatie/ping)[ Packagist](https://packagist.org/packages/spatie/ping)[ Docs](https://github.com/spatie/ping)[ GitHub Sponsors](https://github.com/spatie)[ RSS](/packages/spatie-ping/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (5)Versions (15)Used By (0)

🏓 Run an ICMP ping and get structured results
=============================================

[](#-run-an-icmp-ping-and-get-structured-results)

[![Latest Version on Packagist](https://camo.githubusercontent.com/180d462751be9eb11fdcdc8ba9d4954b85cd75261c848440f0c6bfe7dee89879/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7370617469652f70696e672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/ping)[![Tests](https://camo.githubusercontent.com/b7a4137470b571d4cff563ea0784a8f33c325be0026bd93d262b2ca5194378f5/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7370617469652f70696e672f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/spatie/ping/actions/workflows/run-tests.yml)[![Total Downloads](https://camo.githubusercontent.com/dbad69ef356419402e25d1f7d334020aaf2ba14bb61d85f69f4cc3e8565b1ffa/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7370617469652f70696e672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/ping)

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
----------

[](#support-us)

[![](https://camo.githubusercontent.com/cd0b881029f9fd31d86460448c284c5b3b425ceae91cbf61f49c01b5aeacfa13/68747470733a2f2f6769746875622d6164732e73332e65752d63656e7472616c2d312e616d617a6f6e6177732e636f6d2f70696e672e6a70673f743d31)](https://spatie.be/github-ad-click/ping)

We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).

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](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).

Installation
------------

[](#installation)

You can install the package via Composer:

```
composer require spatie/ping
```

Usage
-----

[](#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

[](#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

[](#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

[](#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

[](#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

[](#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

[](#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
--------------

[](#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
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [Freek Van der Herten](https://github.com/freekmurze)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

56

—

FairBetter than 98% of packages

Maintenance86

Actively maintained with recent releases

Popularity45

Moderate usage in the ecosystem

Community15

Small or concentrated contributor base

Maturity61

Established project with proven stability

 Bus Factor1

Top contributor holds 82% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~20 days

Recently: every ~52 days

Total

12

Last Release

98d ago

Major Versions

0.0.6 → 1.0.02025-07-13

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/7535935?v=4)[Spatie](/maintainers/spatie)[@spatie](https://github.com/spatie)

---

Top Contributors

[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (50 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (5 commits)")[![AlexVanderbist](https://avatars.githubusercontent.com/u/6287961?v=4)](https://github.com/AlexVanderbist "AlexVanderbist (2 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (2 commits)")[![alexjustesen](https://avatars.githubusercontent.com/u/1144087?v=4)](https://github.com/alexjustesen "alexjustesen (1 commits)")[![thecaliskan](https://avatars.githubusercontent.com/u/13554944?v=4)](https://github.com/thecaliskan "thecaliskan (1 commits)")

---

Tags

monitoringnetworkingpingspatieping

###  Code Quality

TestsPest

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/spatie-ping/health.svg)

```
[![Health](https://phpackages.com/badges/spatie-ping/health.svg)](https://phpackages.com/packages/spatie-ping)
```

###  Alternatives

[spatie/laravel-activitylog

A very simple activity logger to monitor the users of your website or application

5.8k45.4M309](/packages/spatie-laravel-activitylog)[spatie/laravel-health

Monitor the health of a Laravel application

86910.0M83](/packages/spatie-laravel-health)[spatie/flare-client-php

Send PHP errors to Flare

176148.0M15](/packages/spatie-flare-client-php)[spatie/laravel-http-logger

A Laravel package to log HTTP requests

6744.4M11](/packages/spatie-laravel-http-logger)[spatie/laravel-server-monitor

Monitor servers

844280.4k6](/packages/spatie-laravel-server-monitor)[spatie/laravel-uptime-monitor

A powerful, easy to configure uptime monitor

1.1k234.4k8](/packages/spatie-laravel-uptime-monitor)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
