grzegorz
grzegorz

Reputation: 340

How to change socket's listening port after accept() was called?

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?

Upvotes: 2

Views: 1932

Answers (1)

user207421
user207421

Reputation: 310980

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?

Upvotes: 3

Related Questions