0

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.

Vaibhav Mishra
  • 11,384
  • 12
  • 45
  • 58
  • 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 Answers2

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
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