Jump to content

Ping An IP Address And Get Response Time


JustinK101

Recommended Posts

Looking for a simple block of code to ping an IP address from PHP and a linux server. Also, I would like the response time.

 

Something like:

 

$resut = ping("232.343.22.2");

 

//true

echo $result[0];

 

//85ms

echo $result[1];

 

Thanks.

You should use Linux's built in ping program, to save coding and time.

$address = 'www.phpfreaks.com'; //Can be IP or server.
$ping = system("ping $address");
echo '<pre>';
echo $ping;

Note you can use regex to extract what you want from the results.. txt2re.com should be a simple option if you don't know regex.

Thanks for the replies. Any benefit of using exec() vs system(). I was looking at the PHP documentation but couldn't figure out the difference. What about creating a socket connection? What is the best possible way to do this? Thanks again.

 

 

system is probably the most straight forward. If you want to narrow down the result some (providing your on Linux) you could use something like....

 

function ping($arg) {
  return system("ping -c 1 $arg | tail -n 2 | head -n 1 | awk '{print $10}'");
}

 

Of course, this won't be very portable because it relies on ping, tail, head and awk, but it will return the request time in ms.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.