spatie/ping
Run ICMP pings in PHP and get structured results. Spatie Ping wraps the system ping command to report success/error status, packets sent/received, loss percentage, min/max/avg response times, and per-reply lines for easy monitoring and diagnostics.
composer require spatie/ping
8.8.8.8):
use Spatie\Ping\Ping;
$result = (new Ping('8.8.8.8'))->run();
if ($result->isSuccess()) {
echo "Host is reachable! Avg RTT: {$result->averageTimeInMs()}ms";
} else {
echo "Host unreachable: {$result->error()?->value}";
}
vendor/spatie/ping/src/ for core classes (Ping, PingResult).vendor/spatie/ping/README.md for quick-start examples.Basic Ping Checks:
// Check if a host is online (default: 4 packets, 1s interval)
$ping = new Ping('example.com');
$result = $ping->run();
// Conditional logic
if ($result->isSuccess()) {
$this->markHostAsOnline($result->host());
}
Customized Ping Configurations:
// Fluent interface for reusability
$ping = (new Ping('db.example.com'))
->timeoutInSeconds(2) // Fail fast
->count(3) // Minimal packets
->packetSizeInBytes(128); // Larger payload for latency testing
$result = $ping->run();
IPv6/IPv4 Forced Pings:
use Spatie\Ping\Enums\IpVersion;
// Force IPv6
$result = (new Ping('ipv6.google.com'))
->ipVersion(IpVersion::IPv6)
->run();
Bulk Ping Operations:
$hosts = ['google.com', 'github.com', 'nonexistent.example'];
$results = collect($hosts)->map(fn($host) => (new Ping($host))->run());
$results->filter(fn($r) => $r->isSuccess())
->each(fn($r) => $this->logSuccess($r->host()));
Error Handling:
try {
$result = (new Ping('malformed-host'))->run();
} catch (\RuntimeException $e) {
report($e); // Log to Laravel's error system
}
Laravel Commands:
use Illuminate\Console\Command;
use Spatie\Ping\Ping;
class PingCommand extends Command {
protected $signature = 'ping:check {host}';
public function handle() {
$result = (new Ping($this->argument('host')))->run();
$this->line($result->isSuccess()
? "✅ {$result->host()} is reachable (Avg: {$result->averageTimeInMs()}ms)"
: "❌ {$result->host()} failed: {$result->error()?->value}");
}
}
Queueable Jobs:
use Spatie\Ping\Ping;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
class PingJob implements ShouldQueue {
use Queueable;
public function handle() {
$result = (new Ping(config('services.db.host')))->run();
if (!$result->isSuccess()) {
$this->notifyAdmins($result);
}
}
}
API Responses:
return response()->json([
'status' => $result->isSuccess() ? 'online' : 'offline',
'data' => $result->toArray(),
]);
Cross-Platform Quirks:
-4/-6 flags (use IpVersion::Auto or omit).showLostPackets(true) only works on Linux (ignored elsewhere).Timeout Handling:
->timeoutInSeconds(10)
Packet Loss Edge Cases:
packetsReceived() === 0, check error() for HostnameNotFound or NetworkUnreachable.IPv6 Limitations:
::1) may fail with InvalidArgumentException. Validate IPs first:
if (!filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
throw new \InvalidArgumentException("Invalid IPv6 address");
}
Raw Output Parsing:
$result->raw directly. Use structured methods like $result->lines() for reliability.Verbose Output:
$result = (new Ping('host'))
->showLostPackets(true) // Linux only
->run();
$this->log($result->raw); // Inspect raw command output
Common Errors:
| Error Enum | Cause | Fix |
|---|---|---|
HostnameNotFound |
DNS resolution failed | Check /etc/hosts or DNS |
NetworkUnreachable |
Firewall/route issue | Test with ping -c 1 host |
CommandExecutionFailed |
System ping command missing |
Install iputils-ping (Linux) |
InvalidArgumentException |
Malformed host/IP | Validate input |
Performance:
count for quick checks (e.g., ->count(2)).intervalInSeconds to avoid packet collisions on congested networks.Custom Error Handling:
$result = (new Ping('host'))->run();
if ($result->hasError()) {
match ($result->error()) {
\Spatie\Ping\Enums\PingError::HostnameNotFound => $this->handleDnsFailure(),
default => $this->handleGenericFailure(),
};
}
Result Transformation:
$result->toArray(); // Serialize for storage
PingResult::fromArray($serializedData); // Reconstruct
Mocking for Tests:
// Use Pest's fake() or Laravel's Mockery
$mockPing = Mockery::mock(Ping::class);
$mockPing->shouldReceive('run')
->andReturn(new PingResult(/* ... */));
Logging:
$this->logger->info('Ping stats', [
'host' => $result->host(),
'rtt_avg' => $result->averageTimeInMs(),
'loss' => $result->packetLossPercentage(),
]);
Configuration:
config() or environment variables:
config(['ping.default_timeout' => 3]);
How can I help you explore Laravel packages today?