{"record":{"id":"7931678d960e72b5","repo":"karatelabs/karate","slug":"failed-to-find-free-port","errorCode":null,"errorMessage":"failed to find free port","messagePattern":"failed to find free port","errorType":"exception","errorClass":"RuntimeException","httpStatus":null,"severity":"error","filePath":"karate-core/src/main/java/io/karatelabs/process/PortUtils.java","lineNumber":118,"sourceCode":"                }\n                logger.trace(\"HTTP {} returned {} (attempt {})\", url, response.statusCode(), i + 1);\n            } catch (Exception e) {\n                logger.trace(\"HTTP {} not available (attempt {}): {}\", url, i + 1, e.getMessage());\n            }\n            sleep(intervalMs);\n        }\n        logger.warn(\"HTTP {} not available after {} attempts\", url, attempts);\n        return false;\n    }\n\n    /**\n     * Find a free port.\n     */\n    public static int findFreePort() {\n        try (ServerSocket socket = new ServerSocket(0)) {\n            return socket.getLocalPort();\n        } catch (Exception e) {\n            throw new RuntimeException(\"failed to find free port\", e);\n        }\n    }\n\n    private static void sleep(int millis) {\n        try {\n            Thread.sleep(millis);\n        } catch (InterruptedException e) {\n            Thread.currentThread().interrupt();\n        }\n    }\n\n}\n","sourceCodeStart":100,"sourceCodeEnd":131,"githubUrl":"https://github.com/karatelabs/karate/blob/a22eb90246d958d15a47bf436693d0121ad2812d/karate-core/src/main/java/io/karatelabs/process/PortUtils.java#L100-L131","documentation":"PortUtils.findFreePort() asks the OS for an ephemeral port by binding a ServerSocket to port 0 and returning its local port. If binding fails (socket subsystem unavailable, permission/security restrictions, resource exhaustion), it throws 'failed to find free port' wrapping the underlying exception.","triggerScenarios":"Calling PortUtils.findFreePort() when ServerSocket(0).bind fails - typically because the operating system denied socket creation, ephemeral port ranges are exhausted, or a security manager/firewall blocks opening server sockets.","commonSituations":"Running tests inside restricted containers/CI sandboxes without network socket permissions, heavy parallel test suites exhausting ephemeral ports (TIME_WAIT buildup), or misconfigured ephemeral port ranges on the host.","solutions":["Read the wrapped cause (e.getCause()) to identify the socket error; fix the underlying OS/network restriction","In containers/CI, ensure the process is allowed to open server sockets (no restrictive network policy or seccomp filter)","Reduce parallelism or reuse a shared port pool if ephemeral ports are exhausted (check with `ss -s` / netstat TIME_WAIT counts)","Retry the call - port exhaustion is often transient"],"exampleFix":null,"handlingStrategy":"retry","validationCode":null,"typeGuard":null,"tryCatchPattern":"int port;\ntry {\n    port = PortUtils.findFreePort();\n} catch (RuntimeException e) {\n    port = fallbackPortAllocator(); // e.g. precomputed range scan\n}","preventionTips":["Cap test parallelism so ephemeral ports are not exhausted","Run socket-dependent tests in environments that permit server sockets","Cache one free port per test class instead of allocating repeatedly","Tune the OS ephemeral port range (net.ipv4.ip_local_port_range)"],"tags":["network","port","socket"],"backgroundTag":"port-exhaustion","analyzedSha":"a22eb90246d958d15a47bf436693d0121ad2812d","analyzedAt":"2026-09-12T09:01:00.220Z","contentChangedAt":"2026-09-12T09:01:00.220Z","schemaVersion":2},"datasetVersion":"2026-09-16T19:17:19.609Z"}