2 votes

How to PING an IP address with PHP?

I'm doing an inventory system of networks between the options I want to add a button to make PING to a given address IP

How do I do it? I am using PHP, although if you can also do in Javascript.

Annex capture for you to understand a little better what I want.

introducir la descripción de la imagen aquí

This my file ping.php:

<?php 
include ("db/conexion.php");
$ip=$_REQUEST['ip'];
$comando = $ip;
$output = shell_exec("ping $comando");
echo $output;
?>

9voto

amenadiel Points 14124

To see... by default PING in linux runs forever, or it keeps pinging until you stop. That's why there's the flag c that allows you to limit the amount of requests. For example, doing a single request:

$output = shell_exec("ping -c 1 $ip");

PEEERO that is a detail. I would change your approach for three reasons:

  1. Run a command that is composed of an input from the user is dangerous. Imagine that the parameter ip is 52.7.164.50 ; cat /etc/passwd. The output would give the output of the table plus the contents of a file as sensitive.
  2. In the second place, depending on the PHP installation (configuration, permissions system, etc) may simply not capable to execute commands.
  3. A ping uses the ICMP protocol. A host which serves, for example, a web site, does not have why to have enabled the ICMP requests. The ping will timeout. You assume that the host is down and in reality the machine is powered on but does not respond to ICMP.

Given the above, what I would do would be to use CURL sending a request of type HEAD. Is what is used by services such as NewRelic or Uptime Robot to check a website is up.

In addition, I would use the function filter_var to validate that the input is a valid IP address. The script, which I just tested in my local, would be as follows:

<?php
$ip = $_REQUEST['ip'];

if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $ip);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    // Petición HEAD
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_NOBODY, true);

    $content = curl_exec($ch);

    if (!curl_errno($ch)) {
        $info = curl_getinfo($ch);

        print_r("\nSe recibió respuesta " . $info['http_code'] . ' en ' . $info['total_time'] . " segundos \n");
    } else {
        print_r("\nError en petición: " . curl_error($ch) . "\n");
    }

    curl_close($ch);

} else {
    print_r("\nDirección IP no válida: " . $ip . "\n");
}

I would suggest to do this check using ajax and do the backend to return a json, but the script above will leave you pretty close to what you want to achieve.

2voto

Luis. I have developed the following class that will be used to perform the ping using the ICMP protocol, thanks to the tools native to the OS; I have designed to be heterogeneous with YOU, so that you will work on Linux and Windows, where it detects where it is running, and with respect to the conditioning to react properly. `

class CheckDevice {

    public function myOS(){
        if (strtoupper(substr(PHP_OS, 0, 3)) === (chr(87).chr(73).chr(78)))
            return true;

        return false;
    }

    public function ping($ip_addr){
        if ($this->myOS()){
            if (!exec("ping -n 1 -w 1 ".$ip_addr." 2>NUL > NUL && (echo 0) || (echo 1)"))
                return true;
        } else {
            if (!exec("ping -q -c1 ".$ip_addr." >/dev/null 2>&1 ; echo $?"))
                return true;
        }

        return false;
    }
}

$ip_addr = "151.101.193.69"; #DNS: www.stackoverflow.com

if ((new CheckDevice())->ping($ip_addr))
    echo "The device exists";
else 
    echo "The device is not connected";

` Here I leave an example where I try to apply a connection to this site, you can do it by using the IP address or DNS.

If you want a better explanation of the code, here I have prepared a small article about it: PHPCentral How to PING from PHP to a remote host?.

It is clear that if the remote host where you want to make the table, have blocked by means of Firewall the ICMP protocol, it will not respond that it is up, it can also be done by performing a sweep of ports to check if the most common are open and we are able to respond, that way it could be done, if it can be done with Sockets directly with PHP, but the joke is that it is the ICMP because in a local network may be that the machines do not have open ports usual which make the requests.

I hope that you work as much as me knight.

A greeting!

1voto

OscarGarcia Points 15361

You can use the exit code of the execution of ping to to know if the machine replied or not, and limit the number of pings performed in linux are infinite by default) in the following way:

<?php 
include 'db/conexion.php';
/* Es mejor que la variable exista para enviarla por referencia */
$salida = 0;
/* Ejecutamos un ping con tres intentos y una espera  máxima de 1sg */
$output = system(
  'ping -c 3 -W 1 ' . escapeshellarg($_REQUEST['ip']),
  $salida
);
/* Si el código de salida es 0 el equipo respondió */
if ($salida === 0) {
  echo "PING correcto";
} else {
  echo "PING mal: " + $output;
}

In addition, I make use of escapeshellarg() to to escape the correct way any character that could be used for an injection attack orders (your code is vulnerable).

As you can see on the page in the manual system():

Warning If you are going to allow data coming from the user are sent to this function, we would have to use escapeshellarg() or escapeshellcmd() to make sure that the user does not try to cheat the system to run arbitrary commands.

0voto

Cristóbal H Points 96

if you are using Linux, you could try to make a call background and receive the response. something like this:

$ip = "ip_prueba";
$output = shell_exec("ping $ip");

if (strpos($output, "recibidos = 0")) {
    echo 'No se pudo encontrar el Host..';
} else {
    echo 'Host conectado..';
}

If afinas a bit more responses, I think this might solve your problem. Greetings

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X