I'd like to change the port a socket is listening on. The problem is that I can't do it as long as a call to accept() is still in progress. I tried closing the socket expecting accept() to exit and return negative value. But it doesn't happen on FreeRTOS. When I close the socket from different thread accept() still executes. The only workaround I came up with is to set a flag in a variable, make a TCP connection and then when accept() finishes, check the flag, bind() with new port nad call listen(). But maybe there is a more elegant method?
-
1What EJP said below is correct. If you are needing to close the socket from a different thread - see this question and answer here: http://stackoverflow.com/questions/2486335/wake-up-thread-blocked-on-accept-call – selbie Aug 13 '14 at 19:11
-
Using `select()` to know when to call `accept()` is the right way to go in this situation. Don't `accept()` a new client until `select()` says to. Then "wake up" `select()` when you need to close the old listening before opening a new listening socket. – Remy Lebeau Aug 13 '14 at 20:17
1 Answers
I'd like to change the port a socket is listening on.
You can't. You have to close the current listening socket and then open a new listening socket.
The problem is that I can't do it as long as a call to accept() is still in progress.
You have to unblock accept()
first, then you can close the listening socket.
I tried closing the socket
That's the right way to implement the requirement, but it doesn't constitute changing the port that the socket is listening on. You have to create a new socket listening on the new port.
I would create the new socket and get it into operation and set a flag saying not to accept any further connections on the old socket: when accept()
on the old socket finally unblocks, check the flag, and if it's set then close the accepted connection and the old listening socket and exit that accept loop and thread.
It's a strange requirement. What's the purpose?

- 555,201
- 31
- 458
- 770

- 305,947
- 44
- 307
- 483
-
The requirement is to have configurable listening port. The port is for binary protocol, configuration is through web interface. My first sentence could have been misleading. I just need to stop listening on one port and start listening on a new one. It doesn't have to be the same socket. Your solution is an interesting idea but requires creating the new socket somewhere outside the server task/thread. Doing it in web server task or a new task for binary protocol leads to a messy code. That's why I need to unblock accept() on demand so the task can deal with creating new socket by itself. – grzegorz Aug 13 '14 at 20:44
-
It doesn't 'require creating a new socket somewhere outside the server task/thread'. – user207421 Jan 19 '16 at 00:46