I created a program which listens to particular socket in python, however I ctrl+c'd script which resulted in .close() nor called, however how can I free the socket now.
Asked
Active
Viewed 154 times
0
-
Are you asking how can free the socket now? Or how can you free the socket if the termination signal is recd.? – Devraj Sep 09 '12 at 05:02
2 Answers
3
The socket is closed when the process exits. The port it was using may hang around for a couple of minutes, that's normal, then it will disappear. If you need to re-use the port immediately, set SO_REUSEADDR before binding or connecting.

user207421
- 305,947
- 44
- 307
- 483
-
-
@VaibhavMishra Why? It's well documented. That would just be repeating someone else's work. Look it up. – user207421 Aug 15 '23 at 04:46
0
Set the SO_REUSEADDR
socket option before calling the bind
method, like this:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
That will instruct the socket to freely reuse the ports left in a waiting state by recent runs of the program.
Or, use the SocketServer.TCPServer
class from the standard library, which will automatically do this if you set the allow_reuse_address
property on the server instance to a true value.

user4815162342
- 141,790
- 18
- 296
- 355