Again, it's up to the OS exactly how the port is reclaimed, it may not be instantaneous.
Are you finding ports not being closed when a socket is closed?
Because again that's the OSes job, and it should be fairly quick.
Sockets don't open or close ports in general, they just connect to a port number specified by the user. The socket connection can then determine if the port is opened or not. And no, ports do not close when closing a socket. Thanks
A listening socket requests a port, which the OS supplies (assuming it's not in use).
When it closes I thought it handed that port back to the OS, which would close it at some point.
Happy to be corrected, since it's been a couple of decades(+) since I had to do this stuff in any significant way.