Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make PHP socket_connect timeout

I have a small application I created to analyze the network connection. It runs from a browser and connects to a local PHP/Apache server. It then asks PHP to send a ping packet through a raw socket. THe problem is that if the host I am trying to ping isn't alive or won't answer to pings, we never get an answer from the server.

I beleave the socket request lives until apache is restarted. I have been getting mixed results from my application lately and I am blaming apache using too many sockets. Currently I have set the AJAX call's timeout and I was happy with it. But I really need to make PHP do the timeouting so that I won't have 500,000 sockets open to an unreachable host.

Some sample code:

$sockconn = @socket_connect($socket, $target, null);
if(!$sockconn)
{
    $raw['error'] = socket_strerror(socket_last_error());
    $raw['status'] = false;
    return $raw;
}

This is the function that won't timeout. I need to get it to timeout. Also PHP script execution time DOES NOT affect sockets.

I am clueless.

like image 951
Axel Latvala Avatar asked Aug 09 '12 10:08

Axel Latvala


1 Answers

You can set timeouts for reading and sending using the following options:

socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => 1, 'usec' => 0));
socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 1, 'usec' => 0));

Alternatively, you can use non-blocking sockets and periodically poll the socket to see if the remote host responded.

like image 127
Sjoerd Avatar answered Nov 15 '22 16:11

Sjoerd