Page 1 of 1
Closing off sockets in PHP
Posted: Tue Nov 07, 2006 8:18 am
by impulse()
I've just ran this code:
Code: Select all
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($socket, '1.1.1.1', 1);
socket_listen($socket);
while ($connection = socket_accept($socket)) {
for ($i = 0; $i < 10000; $i++) {
socket_write($connection, "Go away");
}
}
And when the user that connects to the the script exists it leaves the port open. If I try and run the same script again I get the following message
PHP Warning: socket_bind(): unable to bind address [98]: Address already in use in /var/www/html/php/test/socketread.php on line 5
Although if I try and telnet to myself on the port it doesn't seem to be open.
Posted: Tue Nov 07, 2006 8:22 am
by feyd
I'm not seeing a
socket_close().
Posted: Tue Nov 07, 2006 8:23 am
by Chris Corbyn
I've had this same issue before. Leaving it for a minute or two gets it working again but it's very confusing why PHP sees it as a bound socket because you're right, when you look into it it's not actually bound at all.
Posted: Tue Nov 07, 2006 12:45 pm
by Cameri
Well, the way I see it, your script may have bound to the ip/port one time, and since you never closed the socket (note: check feyd's post), you can't bind to it again, unless, you restart your machine, or wait some x time for it to unbind. There's probably a program to unbind addresses but I don't know any.
Posted: Tue Nov 07, 2006 5:17 pm
by printf
If your using bind and doing something that is not normal, like exiting a bind socket then the socket will remain in a bind state until the timeout is encounter. Bind within a script should only be used for certain applications, and surly not when doing what your example does. If you must do non-standard socket coding then use socket_set_option() to test if the socket is in a bind state and if it is, set the REUSE flag so it can be freed and used again. But as feyd said, socket_close(), should always be used for any socket stream.
printf
Posted: Wed Nov 08, 2006 5:02 am
by Mordred
Even better:
Code: Select all
socket_shutdown($socket, 2);
socket_close($socket);
Posted: Wed Nov 08, 2006 5:24 am
by timvw
printf wrote:set the REUSE flag so it can be freed and used again.
I agree that setting SO_REUSEADDR is essential... (Otherwise it will keep a serious while before the socket becomes available again, even if you closed it...)