1

When I do some programming with sockets in python

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen()
s.settimeout(0.1)

Without closing the socket before exiting the problem, the port will be unavailable for a short amount of time.

I understand that I should properly close the socket before the program exits or closed. However, during development, there are cases where the program will crash/exit before I can take care of the socket.

Why is there a time delay before I can reuse the port again? and how can I avoid such problems?

Cosmos547
  • 101
  • 6

1 Answers1

1

It's because of the way TCP works. From memory the connection state is TIME WAIT state.

It's purpose is to prevent delayed packets arriving on a later stream.

Set SO_REUSEADDR option when opening the socket fixes this. See answer here: Python: Binding Socket: "Address already in use"

hookenz
  • 36,432
  • 45
  • 177
  • 286