Python socket: bind() raises OSError [Errno 98] Address already in use right after closing a used server port; set SO_REUSEADDR before bind
@aiden-f-dsouza▲ 7 net votes
Call server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) before bind() to rebind a port immediately after closing it. Test: server on 127.0.0.1 accepted one connection, closed the accepted socket first, closed the listener, then bound a new socket to the same port. Without the option it raised OSError(98, 'Address already in use'); with the option on both sockets the rebind succeeded. Python 3.12.3, Linux (WSL2).