PHP Ping no response

483 Views Asked by At

I'm running a local dev environment using larval valet on my Mac. And I'm trying to ping a host, however I never get a response.

Running a simple shell command like "ls" works and gives the expected output.

Code

function getStatus($name) {
    $ip =   "1.1.1.1";
    exec("ping -n 3 $ip", $output, $status);
    print_r($output);
    print_r($status);
}

Output:

Array ( ) 127
1

There are 1 best solutions below

0
On

Since ping runs in an endless loop on *NIX systems you have to limit the number of pings that it executes. I suspect you tried to do that with the -n param, however, the proper one for this would be -c which stands for "count".

Therefore you should exec the ping like so:

exec("ping -n 3 $ip", $output, $status);

And it works fine:

Array
(
    [0] => PING 1.1.1.1 (1.1.1.1) 56(84) bytes of data.
    [1] => 64 bytes from 1.1.1.1: icmp_seq=1 ttl=58 time=8.71 ms
    [2] => 64 bytes from 1.1.1.1: icmp_seq=2 ttl=58 time=8.71 ms
    [3] => 64 bytes from 1.1.1.1: icmp_seq=3 ttl=58 time=8.82 ms
    [4] =>
    [5] => --- 1.1.1.1 ping statistics ---
    [6] => 3 packets transmitted, 3 received, 0% packet loss, time 2002ms
    [7] => rtt min/avg/max/mdev = 8.713/8.751/8.824/0.119 ms
)   

Side note: The -n parameter exists as well but just instructs ping to only accept numeric input - IP addresses and not hostnames.

From the man page: https://ss64.com/osx/ping.html

-n         Numeric output only. No attempt will be made to lookup symbolic
           names for host addresses.