angelcamposm / ping

A Ping package for Laravel
MIT License
55 stars 10 forks source link

ErrorException for unreachable host #33

Open goldjunge4 opened 2 months ago

goldjunge4 commented 2 months ago

Hello

i am running your package on an Ubuntu Server and it is running perfect if the host is reachable, but if the host is unreachable i get following Exception:

ErrorException

Undefined array key 1

at vendor/acamposm/ping/src/Parsers/PingParserForLinux.php:102 98▕ 99▕ foreach ($ping as $row) { 100▕ if (str_contains('Unreachable', $row)) { 101▕ $data = explode(': ', str_replace(' ms', '', $row)); ➜ 102▕ $items = explode(' ', $data[1]); 103▕ 104▕ $key = (int) explode('=', $items[0])[1]; 105▕ $value = (float) explode('=', $items[2])[1]; 106▕

I am working on Laravel 11 and run the command:

$command = (new PingCommandBuilder('x.x.x.x'));

// Pass the PingCommand instance to Ping and run...
        $ping = (new Ping($command))->run();

Do you know what i can do the get a correct result on unreachable devices?

Thanks

mrozek90 commented 2 months ago

I have the same problem.

Easiest way: try-catch

try {
$command = (new PingCommandBuilder('x.x.x.x'));

// Pass the PingCommand instance to Ping and run...
        $ping = (new Ping($command))->run();
} catch (Exception $e) {
       Log::error($e); 
}

I'll try to solve that problem. In touch!

mrozek90 commented 2 months ago

Works for me on Ubuntu.

 try {
                    $monitoring = (new PingCommandBuilder('$ipAddress'))
                        ->count(2)
                        ->interval(1)
                        ->ttl(128);
                    $ping = (new Ping($monitoring))->run();

//looking for response
                    if ($ping->host_status == 'Ok') {                    

                         Log::info('Host is online!');
                    } else {
//no response
                        Log::error('Host is unreachable');

                    }
     } catch (Exception $e) {

//0 errors happened. Undefined array key 1 exception not shown.
                    Log::error('Error! Host is unreachable'); // or  Log::error($e);
     }

Tested IP range: 192.168.0.1/24

Needs more tests, ex. offline gateway. Hope, it solve this problem.

----- edit ----- Tested more.

Ok, fine... I tried ping with ->count(2). If count is less than 3 array is not returned:

https://github.com/angelcamposm/ping/blob/b0a209005b9db96bbb9a68703cdd5b93d454c448/src/Ping.php#L98

Sooo.... in my opinion, try-catch is best way to avoid bug. Exception = host offline.