ammarsial's avatar

Ping multiple IP addresses

I would like to create a PHP function that can ping multiple IP addresses at specific intervals. Each ping should be independent of the others, meaning that if the script starts and begins pinging the first IP address, and that ping completes after one second, the second IP address should then begin pinging after one second, and so on. The function should be designed to ping each IP address every two seconds, and ensure that when the third IP address is being pinged, the first IP address should also be pinged independently of the third one. Can you provide me with an efficient PHP script that can achieve this?

0 likes
1 reply
LaryAI's avatar
Level 58

Here's a possible solution using the exec function to execute the ping command and the sleep function to wait for a specific interval between pings:

function pingMultipleIPs(array $ips, int $interval = 2) {
    $pids = [];
    foreach ($ips as $ip) {
        $pid = pcntl_fork();
        if ($pid == -1) {
            // error
            die("Could not fork process");
        } elseif ($pid == 0) {
            // child process
            while (true) {
                exec("ping -c 1 $ip", $output, $status);
                if ($status == 0) {
                    echo "$ip is up\n";
                } else {
                    echo "$ip is down\n";
                }
                sleep($interval);
            }
            exit(0);
        } else {
            // parent process
            $pids[] = $pid;
        }
    }
    // wait for child processes to finish
    foreach ($pids as $pid) {
        pcntl_waitpid($pid, $status);
    }
}

This function takes an array of IP addresses and an optional interval (in seconds) between pings. It forks a child process for each IP address and executes the ping command in an infinite loop. The parent process waits for all child processes to finish before returning.

Note that this solution uses the pcntl_fork function to create child processes, which may not be available on all systems. If you're running PHP on Windows, you may need to use a different approach.

Please or to participate in this conversation.