{"record":{"id":"bebe1c832b37cc4d","repo":"SeleniumHQ/selenium","slug":"can-t-find-free-port-unable-to-bind-to-ipv4-or-ip","errorCode":null,"errorMessage":"Can't find free port (Unable to bind to IPv4 or IPv6)","messagePattern":"Can't find free port \\(Unable to bind to IPv4 or IPv6\\)","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"critical","filePath":"py/selenium/webdriver/common/utils.py","lineNumber":50,"sourceCode":"\n    First try IPv4, but use IPv6 if it can't bind (IPv6-only system).\n    \"\"\"\n    free_socket = None\n    try:\n        # IPv4\n        free_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        free_socket.bind((\"127.0.0.1\", 0))\n    except OSError:\n        if free_socket:\n            free_socket.close()\n        # IPv6\n        try:\n            free_socket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)\n            free_socket.bind((\"::1\", 0))\n        except OSError:\n            if free_socket:\n                free_socket.close()\n            raise RuntimeError(\"Can't find free port (Unable to bind to IPv4 or IPv6)\")\n    try:\n        port: int = free_socket.getsockname()[1]\n    except Exception as e:\n        raise RuntimeError(f\"Can't find free port: ({e})\")\n    finally:\n        free_socket.close()\n    return port\n\n\ndef find_connectable_ip(host: str | bytes | None, port: int | None = None) -> str | None:\n    \"\"\"Resolve a hostname to an IP, preferring IPv4 addresses.\n\n    We prefer IPv4 so that we don't change behavior from previous IPv4-only\n    implementations, and because some drivers (e.g., FirefoxDriver) do not\n    support IPv6 connections.\n\n    If the optional port number is provided, only IPs that listen on the given\n    port are considered.","sourceCodeStart":32,"sourceCodeEnd":68,"githubUrl":"https://github.com/SeleniumHQ/selenium/blob/aa36b38e696a0909e973bdf5e2f9031ffe842c4b/py/selenium/webdriver/common/utils.py#L32-L68","documentation":"Raised by utils.free_port() when binding a TCP socket to 127.0.0.1:0 (IPv4) fails with OSError AND the IPv6 fallback bind to [::1]:0 also fails. free_port is called by Service.__init__ (default port=0) to let the OS assign an ephemeral port. Failing both families means the host cannot allocate any loopback listener socket at all.","triggerScenarios":"A sandbox/container with loopback networking disabled, an environment where both IPv4 and IPv6 loopback binds are denied by seccomp/AppArmor, or extreme ephemeral-port exhaustion. Extremely rare on normal hosts.","commonSituations":"Overly restrictive container security profiles (no network namespace loopback), locked-down CI runners, or test harnesses that mock out the socket module incorrectly. Also seen in some minimal BSD jails.","solutions":["Pass an explicit port to the Service to avoid the free_port() call: Service(port=9515).","Loosen the container/jail networking so loopback binds are permitted.","If running under a custom socket-mocking test layer, ensure socket.socket().bind is not unconditionally raising.","Check for ephemeral port exhaustion: raise net.ipv4.ip_local_port_range or reduce TIME_WAIT sockets."],"exampleFix":"# before — free_port() fails in a locked container\nservice = Service(executable_path='/path/driver')  # port defaults to 0 -> free_port()\n\n# after — supply a fixed port\nservice = Service(executable_path='/path/driver', port=9515)","handlingStrategy":"fallback","validationCode":"null","typeGuard":"null","tryCatchPattern":"import socket\ntry:\n    s = socket.socket(); s.bind(('127.0.0.1', 0)); s.close()\nexcept OSError:\n    port = 9515  # fixed fallback\nelse:\n    port = 0  # let Service pick","preventionTips":["In locked containers, pass a fixed port to Service rather than relying on free_port().","Ensure loopback networking is enabled in your container/jail profile.","Monitor ephemeral port usage to detect exhaustion early."],"tags":["network","port","environment","container","loopback"],"backgroundTag":null,"analyzedSha":"aa36b38e696a0909e973bdf5e2f9031ffe842c4b","analyzedAt":"2026-08-14T02:32:32.244Z","schemaVersion":2},"datasetVersion":"2026-08-14T05:17:29.042Z"}