Java HTTP Port Find isPortAvailable(String portNumber)

Here you can find the source of isPortAvailable(String portNumber)

Description

Function to check if a port is available

License

Open Source License

Parameter

Parameter Description
portNumber to check (as a String)

Exception

Parameter Description
NumberFormatException an exception

Return

true if port is available, false otherwise

Declaration

public static boolean isPortAvailable(String portNumber) throws NumberFormatException 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright 2012 Google Inc. All Rights Reserved.
 * /*from  www  .  j  a  v  a 2  s .c  o 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
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/

import java.io.IOException;
import java.net.ServerSocket;

public class Main {
    /**
     * Function to check if a port is available
     * 
     * @param portNumber to check (as a String)
     * @return true if port is available, false otherwise
     * @throws NumberFormatException
     */
    public static boolean isPortAvailable(String portNumber) throws NumberFormatException {

        final int port = Integer.parseInt(portNumber);

        ServerSocket ss = null;
        try {
            ss = new ServerSocket(port);
            ss.setReuseAddress(true);
            return true;
        } catch (IOException e) {
            //
        } finally {
            if (ss != null) {
                try {
                    ss.close();
                } catch (IOException e) {
                    // probably shouldn't get here
                }
            }
        }

        return false;
    }
}

Related

  1. isPortAvailable(String host, int port)
  2. isPortAvailable(String host, int port)
  3. isPortAvailable(String hostname, int port)
  4. isPortAvailable(String hostName, int port)
  5. isPortAvailable(String hostname, int port)
  6. isPortBound(int port)
  7. isPortFree(int port)
  8. isPortFree(int port)
  9. isPortFree(int portNumber)