user1288533 user1288533 - 1 year ago 319
PHP Question

how to ping a server port with php?

i want a php code that give you the ping of and ip:port
i have found a similar one but it only work for web site not on ip:port


function ping($host, $port, $timeout)
$tB = microtime(true);
$fP = fSockOpen($host, $port, $errno, $errstr, $timeout);
if (!$fP) { return "down"; }
$tA = microtime(true);
return round((($tA - $tB) * 1000), 0)." ms";

//Echoing it will display the ping if the host is up, if not it'll say "down".
echo ping("", 80, 10);


++ i want this for game server
this mean i type ip and port and i get the ping
thats the idea of it

Answer Source

I think the answer to this question pretty much sums up the problem with your question.

If what you want to do is find out whether a given host will accept TCP connections on port 80, you can do this:

$host = ''; 
$port = 80; 
$waitTimeoutInSeconds = 1; 
if($fp = fsockopen($host,$port,$errCode,$errStr,$waitTimeoutInSeconds)){   
   // It worked 
} else {
   // It didn't work 

For anything other than TCP it will be more difficult (although since you specify 80, I guess you are looking for an active HTTP server, so TCP is what you want). TCP is sequenced and acknowledged, so you will implicitly receive a returned packet when a connection is successfully made. Most other transport protocols (commonly UDP, but others as well) do not behave in this manner, and datagrams will not be acknowledged unless the overlayed Application Layer protocol implements it.

The fact that you are asking this question in this manner tells me you have a fundamental gap in your knowledge on Transport Layer protocols. You should read up on ICMP and TCP, as well as the OSI Model.

Also, here's a slightly cleaner version to ping to hosts.

// Function to check response time
function pingDomain($domain){
    $starttime = microtime(true);
    $file      = fsockopen ($domain, 80, $errno, $errstr, 10);
    $stoptime  = microtime(true);
    $status    = 0;

    if (!$file) $status = -1;  // Site is down
    else {
        $status = ($stoptime - $starttime) * 1000;
        $status = floor($status);
    return $status;