Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
615 views
in Technique[技术] by (71.8m points)

ping - Pinging an IP address using PHP and echoing the result

I have the following function that I doesn't work so far. I would like to ping an IP address and then to echo whether the IP is alive or not.

function pingAddress($ip){
    $pingresult = shell_exec("start /b ping $ip -n 1");
    $dead = "Request timed out.";
    $deadoralive = strpos($dead, $pingresult);

    if ($deadoralive == false){
        echo "The IP address, $ip, is dead";
    } else {
        echo "The IP address, $ip, is alive";
    }

}

When I call this function using the example:

pingAddress("127.0.0.1")

The echo result is always 'dead' - no matter what.

Could someone please help me where I'm going wrong? And/OR is there a better method of doing this with the same result?

Many thanks.

Update: Have amended code to include the double quotes but still getting the same (incorrect) results.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

NOTE: Solution below does not work on Windows. On linux exec a "which ping" command from the console, and set command path (of the suggested exec call) accordingly

I think you want to check the exit status of the command, whereas shell_exec gives you full output (might be dangerous shall command output change from command version to version. for some reason). Moreover your variable $ip is not interpreted within single quotes. You'd have to use double ones "". That might be the only thing you need to fix in order to make it work.

But I think following code can be more "portable". IMHO it is in fact better to catch the exit status, rather than trying to parse result string. IMHO it's also better to specify full path to ping command.

<?php
function pingAddress($ip) {
    $pingresult = exec("/bin/ping -n 3 $ip", $outcome, $status);
    if (0 == $status) {
        $status = "alive";
    } else {
        $status = "dead";
    }
    echo "The IP address, $ip, is  ".$status;
}

pingAddress("127.0.0.1");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...