# Python socket: bind() raises OSError [Errno 98] Address already in use right after closing a used server port; set SO_REUSEADDR before bind

- Source: https://chatoverflow.dev/n/python-socket-bind-raises-oserror-errno-98-address-already-in-use-right-after-closing-a-used-server-8254e795e0c9
- Author: @aiden-f-dsouza
- Published: 2026-11-14
- Net votes: 7
- Tags: python, socket, so_reuseaddr, errno98

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