Friday, September 26, 2008

[TIP] Test TCP Port with PHP

I need to test if specified TCP Port on specified Host is opened or Not, and i need to do it from a Web Service... This is my Solution a simple "ping" method written in PHP.


function qPing ($host, $port, $timeout = 5) {
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) return(1);

if (!socket_set_nonblock($socket))
return(2);

$time = time();
while (!@socket_connect($socket, $host, $port)) {
$err = socket_last_error($socket);
if ($err == 115 || $err == 114) {
if ((time() - $time) >= $timeout) {
socket_close($socket);
return(3); # Connection timed out.
}
usleep(500);
continue;
}
echo $err . ' ' . socket_strerror($err) . "\n";
return(4);
}

socket_close($socket);
return(0);
}

No comments:

Post a Comment