I'm trying to do actual, genuine ping using ICMP packets, natively in PHP. Right now I'm using exec to run the ping
command, but you never quite know what it's going to output, which makes it very hard to format the results for web. Different network setups can result in some crazy output. So I wrote my own pinger using socket_create() (with help from the manual comments), but that also doesn't work. Apparently you can't create a raw socket unless your apache server is running as root. That's not a good solution either.
This is a web tool where visitors run a ping on themselves, meaning they visit the page, and my server pings them, and outputs the results. So I can't just open a tcp connection, close it, and use that as a ping, because who knows if the user has any ports open at all.
There is also a pear package for pinging, but ultimately it is just a wrapper for exec("ping $host");
I may be stuck with my old code, that uses the system ping command. But I just want to be sure there are no other solutions first. Because I really want to do this natively in PHP if I can.
Here is my ping function. It fails with an "unable to create socket [1]" error:
function ping_you()
{
$package = "\x08\x00\x19\x2f\x00\x00\x00\x00\x70\x69\x6e\x67";
$sock = socket_create(AF_INET, SOCK_RAW, 1);
if ($sock === false)
{
echo ">> " . socket_strerror(socket_last_error()) . " <<";
}
socket_bind($sock,OPERATING_IP);
socket_set_option($sock, SOL_SOCKET, SO_RCVTIMEO, array("sec" => 1, "usec" => 0));
socket_connect($sock, $_SERVER['REMOTE_ADDR'], null);
$start_time = microtime(true);
socket_send($sock, $package, strlen($package), 0);
if(@socket_read($sock, 255))
{
$end_time = microtime(true);
return $end_time - $start_time;
}
else
{
return false;
}
socket_close($sock);
}