pythonlinuxsocketsconnectionerrno

Python [Errno 98] Address already in use


In my Python socket program, I sometimes need to interrupt it with Ctrl-C. When I do this, it does close the connection using socket.close().

However, when I try to reopen it I have to wait what seems like a minute before I can connect again. How does one correctly close a socket? Or is this intended?


Solution

  • Yes, this is intended. Here you can read a detailed explanation. It is possible to override this behavior by setting the SO_REUSEADDR option on a socket. For example:

    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)