Java HTTP Port Find isPortInUse(int port)

Here you can find the source of isPortInUse(int port)

Description

Checks if the given port is already used

License

Open Source License

Parameter

Parameter Description
port the port to check

Return

true if the port is used, false if it is available.

Declaration

public static boolean isPortInUse(int port) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2016 Red Hat./* w ww  .ja v a  2  s.co m*/
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Red Hat - Initial Contribution
 *******************************************************************************/

import java.io.IOException;

import java.net.ServerSocket;

public class Main {
    /**
     * Checks if the given port is already used
     * 
     * @param port
     *            the port to check
     * @return <code>true</code> if the port is used, <code>false</code> if it
     *         is available.
     */
    public static boolean isPortInUse(int port) {
        if (port < 0 || port >= 65536) {
            return false;
        }
        try (ServerSocket socket = new ServerSocket(port)) {
            //not in use
            return false;
        } catch (IOException e) {
            return true;//in use
        }
    }
}

Related

  1. isPortFree(int port)
  2. isPortFree(int portNumber)
  3. isPortFree(String hostName, String port)
  4. isPortFreeClient(String hostName, int portNumber)
  5. isPortInUse(final String host, final Integer port)
  6. isPortOnUse(int port)
  7. isPortOpen(int port)
  8. isPortOpen(int port, String host)
  9. isPortOpen(String host, int port)