Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to unlisten on a socket?

Is it possible to unlisten on a socket after you have called listen(fd, backlog)?

Edit: My mistake for not making myself clear. I'd like to be able to temporarily unlisten on the socket. Calling close() will leave the socket in the M2LS state and prevent me from reopening it (or worse, some nefarious program could bind to that socket)

Temporarily unlistening would be a way (maybe not the best way) to signal to an upstream load balancer that this app couldn't accept any more requests for the moment

like image 754
Dave Cheney Avatar asked Oct 02 '08 11:10

Dave Cheney


People also ask

Can a socket send to itself?

A socket cannot emit to itself #2972.


2 Answers

After closing the socket, your programs may still tell you that the socket is "in use", this is because of some weirdiness I don't know exactly about. But the manpage about sockets shows you there is a flag to re-use the same socket, lazily called: "SO_REUSEADDR". Set it using "setsockopt()".

like image 186
gx. Avatar answered Sep 28 '22 06:09

gx.


Some socket libraries allow you to specifically reject incoming connections. For example: GNU's CommonC++: TCPsocket Class has a reject method.

BSD Sockets doesn't have this functionality. You can accept the connection and then immediately close it, while leaving the socket open:

while (running) {

  int i32ConnectFD = accept(i32SocketFD, NULL, NULL);
  while (noConnectionsPlease) {
    shutdown(i32ConnectFD, 2);
    close(i32ConnectFD);
    break;
  }

}
like image 36
Andrew Johnson Avatar answered Sep 28 '22 05:09

Andrew Johnson