private boolean isLocalhostPortAvailable()

in src/main/java/org/apache/sling/maven/kickstart/run/LauncherCallable.java [138:158]


    private boolean isLocalhostPortAvailable(int port) throws IOException {
        // https://stackoverflow.com/questions/46436813/difference-between-a-connection-refused-exception-and-a-timeout-in-httpclient
        Socket clientSocket = new Socket();
        try {
            clientSocket.connect(new InetSocketAddress("127.0.0.1", port), 500);
            // without that, read() call on the InputStream associated with this Socket is infinite
            this.logger.debug("Successfully connected to localhost, port " + port);
            clientSocket.close();
            return true;
        } catch (SocketTimeoutException e) {
            // we ran into a timeout (port most probably blocked by firewall)
            this.logger.debug("Ran into a timeout while connecting to localhost, port " + port, e);
            return false;
        } catch (ConnectException e) {
            // port not bound
            this.logger.debug("Could not connect to localhost, port " + port, e);
            return false;
        } finally {
            clientSocket.close();
        }
    }