Java HTTP Port Find safePort(final String port)

Here you can find the source of safePort(final String port)

Description

Validate the given port is in a valid range, returning 0 if it is invalid.

License

BSD License

Declaration

public static int safePort(final String port) 

Method Source Code

//package com.java2s;
/**// w  ww  .  j  av a2s.  com
 * Copyright (C) 2011-2014 Barchart, Inc. <http://www.barchart.com/>
 *
 * All rights reserved. Licensed under the OSI BSD License.
 *
 * http://www.opensource.org/licenses/bsd-license.php
 */

import java.io.IOException;

import java.net.ServerSocket;

public class Main {
    /**
     * Validate the given port is in a valid range, returning 0 if it is invalid.
     */
    public static int safePort(final String port) {

        try {

            if ("*".equals(port)) {
                return randomPort();
            }

            final int number = Integer.parseInt(port);

            if (number < 0 || number > 65535) {
                return 0;
            } else {
                return number;
            }

        } catch (final Throwable e) {
            return 0;
        }

    }

    private static int randomPort() throws IOException {
        // Find an open local port
        final ServerSocket ss = new ServerSocket(0);
        final int port = ss.getLocalPort();
        ss.close();
        return port;
    }
}

Related

  1. randomFreePort()
  2. read(String host, int port)
  3. readHttpContent(String domain, String resource, int port)
  4. replace(final String host, final int port, final String user, final String program, final String relation, final String dataset, final String format)
  5. resolve(final String desc, final int defaultPort)
  6. searchPort(int number, int even, boolean stream)
  7. selectAvailablePort(int preferedPort)
  8. sendCommand(final String command, final int monitorPort)
  9. sendCommand(String host, Integer port, String cmd)