function check_tcp_active($host, $port) {
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($socket,
SOL_SOCKET,
SO_RCVTIMEO,
array(
"sec"=>0,
"usec"=>500
)
);
$result = @socket_connect($socket, $host, $port);
if ( $result ) {
socket_close($socket);
return(TRUE);
} else {
return(FALSE);
}
}
function find_active_server($array) {
// Format: $array['127.0.0.1']=3306
if ( is_array($array) ) {
foreach ( $array as $host => $port ) {
if ( $this->check_tcp_active($host, $port) ) {
$rval['host']=$host;
$rval['port']=$port;
return($rval);
}
}
}
return(FALSE);
}
$mysqlServers=array(
'127.0.0.1' => 3306,
'192.168.0.10' => 3306,
'192.168.0.11' => 3306,
'192.168.0.12' => 3306,
'192.168.0.13' => 3306,
'192.168.0.14' => 3306,
);
$goodMysqlHost=find_active_server($mysqlServers);
with only a very small amount of work a pseudo random load distribution would be possible. Hope this helps someone 🙂