Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Ping Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require spatie/ping
    
  2. First use case: Verify connectivity to a host (e.g., 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}";
    }
    
  3. Key files to reference:
    • vendor/spatie/ping/src/ for core classes (Ping, PingResult).
    • vendor/spatie/ping/README.md for quick-start examples.

Implementation Patterns

Core Workflows

  1. 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());
    }
    
  2. 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();
    
  3. IPv6/IPv4 Forced Pings:

    use Spatie\Ping\Enums\IpVersion;
    
    // Force IPv6
    $result = (new Ping('ipv6.google.com'))
        ->ipVersion(IpVersion::IPv6)
        ->run();
    
  4. 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()));
    
  5. Error Handling:

    try {
        $result = (new Ping('malformed-host'))->run();
    } catch (\RuntimeException $e) {
        report($e); // Log to Laravel's error system
    }
    

Integration Tips

  • 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(),
    ]);
    

Gotchas and Tips

Pitfalls

  1. Cross-Platform Quirks:

    • macOS: Ignores -4/-6 flags (use IpVersion::Auto or omit).
    • Windows: May require admin privileges for custom packet sizes/TTL.
    • Linux: showLostPackets(true) only works on Linux (ignored elsewhere).
  2. Timeout Handling:

    • Default timeout is 5 seconds. Increase for unreliable networks:
      ->timeoutInSeconds(10)
      
  3. Packet Loss Edge Cases:

    • If packetsReceived() === 0, check error() for HostnameNotFound or NetworkUnreachable.
  4. IPv6 Limitations:

    • Some hosts (e.g., ::1) may fail with InvalidArgumentException. Validate IPs first:
      if (!filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
          throw new \InvalidArgumentException("Invalid IPv6 address");
      }
      
  5. Raw Output Parsing:

    • Avoid parsing $result->raw directly. Use structured methods like $result->lines() for reliability.

Debugging Tips

  1. Verbose Output:

    $result = (new Ping('host'))
        ->showLostPackets(true)  // Linux only
        ->run();
    $this->log($result->raw);   // Inspect raw command output
    
  2. 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
  3. Performance:

    • Reduce count for quick checks (e.g., ->count(2)).
    • Increase intervalInSeconds to avoid packet collisions on congested networks.

Extension Points

  1. Custom Error Handling:

    $result = (new Ping('host'))->run();
    if ($result->hasError()) {
        match ($result->error()) {
            \Spatie\Ping\Enums\PingError::HostnameNotFound => $this->handleDnsFailure(),
            default => $this->handleGenericFailure(),
        };
    }
    
  2. Result Transformation:

    $result->toArray(); // Serialize for storage
    PingResult::fromArray($serializedData); // Reconstruct
    
  3. Mocking for Tests:

    // Use Pest's fake() or Laravel's Mockery
    $mockPing = Mockery::mock(Ping::class);
    $mockPing->shouldReceive('run')
        ->andReturn(new PingResult(/* ... */));
    
  4. Logging:

    $this->logger->info('Ping stats', [
        'host' => $result->host(),
        'rtt_avg' => $result->averageTimeInMs(),
        'loss' => $result->packetLossPercentage(),
    ]);
    
  5. Configuration:

    • Override defaults via config() or environment variables:
      config(['ping.default_timeout' => 3]);
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata