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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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.

 

 

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.