python network_error ai_generated partial

OSError: [Errno 98] Address already in use

ID: python/oserror-address-already-in-use

Also available as: JSON · Markdown
88%Fix Rate
90%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
311 active

Root Cause

Port is occupied by another process. Common with Flask/Django dev servers after crash.

generic

Workarounds

  1. 95% success Find and kill the process using the port: lsof -i :PORT | kill
    lsof -i :8000 | grep LISTEN
    kill -9 <PID>

    Sources: https://docs.python.org/3/library/socket.html

  2. 90% success Set SO_REUSEADDR on the socket to allow immediate reuse
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    Sources: https://docs.python.org/3/library/socket.html#socket.socket.setsockopt

Dead Ends

Common approaches that don't work:

  1. Change the port number every time 60% fail

    Inconvenient and doesn't free the stuck port

  2. Kill all Python processes 65% fail

    May kill unrelated Python processes

Error Chain

Leads to: