JustinK101 Posted August 25, 2009 Share Posted August 25, 2009 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. Quote Link to comment Share on other sites More sharing options...
oni-kun Posted August 25, 2009 Share Posted August 25, 2009 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. Quote Link to comment Share on other sites More sharing options...
trq Posted August 25, 2009 Share Posted August 25, 2009 Have you thought about executing ping via system? Quote Link to comment Share on other sites More sharing options...
oni-kun Posted August 25, 2009 Share Posted August 25, 2009 Have you thought about executing ping via system? Have you thought about reading said posts? lol Quote Link to comment Share on other sites More sharing options...
JustinK101 Posted August 25, 2009 Author Share Posted August 25, 2009 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. Quote Link to comment Share on other sites More sharing options...
trq Posted August 25, 2009 Share Posted August 25, 2009 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. Quote Link to comment Share on other sites More sharing options...
JustinK101 Posted August 25, 2009 Author Share Posted August 25, 2009 thorpe, Tried your code from my Mac terminal: ping -c 1 google.com | tail -n 2 | head -n 1 | awk '{print $10}' Nothing outputted. Quote Link to comment Share on other sites More sharing options...
trq Posted August 25, 2009 Share Posted August 25, 2009 I get 1ms here on Debian. Obviously mac doesn't use GNU tools. You'll need to parse the output yourself. Start with ping and go from there. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.