How do I free up a TCP/IP port?

To free up a TCP/IP port that your application application has previously bound to, either call close() on the listening socket, or exit the application. This is all that needs to be done to make the port available for reuse, but there is a wrinkle: when an application closes a socket (either explicitly or implicitly by exiting), the system puts the TCP connection into what is known as the TIME_WAIT state. Its aim in doing so is to ensure that it can detect any packets that might arrive from the peer afterwards and respond with resets.

By default, the system will not allow any new processes to bind to a local socket on which there are any TCP connections in the TIME_WAIT state, which can persist for up to several minutes after the socket was closed. There is a way around this, namely to set the socket option SO_REUSEADDR on the socket before binding. This must have been set on both the socket that is closed down, and on the new socket, in both cases before the call to bind().

If consistent use of this socket option is not possible, the other alternative is to make sure that no connections from the socket go into TIME_WAIT. It is the connection on the host that initiates the close that goes into TIME_WAIT, while the connection on the other host goes straight to CLOSED after receiving the final ACK. Thus, if you can arrange for the clients to close any TCP connections, then no connections on the server side will hang around in TIME_WAIT, and the TCP port can be reused immediately.

If neither of these options is available, then the port will be available for reuse after TIME_WAIT, if not sooner; this can be as long as 4 minutes, but a more common value is 1 minute.

Related

Blog: Cloudy with a Chance of TCP Drops