Ad

Is It Possible To Unlisten On A Socket?

- 1 answer

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

Ad

Answer

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;
  }

}
Ad
source: stackoverflow.com
Ad