Java HTTP Port Find isServerPortFree(int port)

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

Description

Check whether the specified server socket port is free or not.

License

Apache License

Parameter

Parameter Description
port the port number to be checked

Return

true if the port is free, or false if it is being used by other program.

Declaration

static public boolean isServerPortFree(int port) 

Method Source Code


//package com.java2s;
/*/*  w  w  w  . jav a 2 s  .  com*/
Copyright 2012 James Hu
    
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    
http://www.apache.org/licenses/LICENSE-2.0
    
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 {
    /**
     * Check whether the specified server socket port is free or not. 
     * Be aware that this method is not safe if there are so many programs trying to open server sockets.
     * @param port the port number to be checked
     * @return true if the port is free, or false if it is being used by other program.
     */
    static public boolean isServerPortFree(int port) {
        ServerSocket s;
        try {
            s = new ServerSocket(port);
            s.close();
        } catch (IOException e) {
            return false;
        }
        return true;
    }
}

Related

  1. isPortUsing(String host, int port)
  2. isReachable(final String hostName, int port, int timeout)
  3. isReachableByPing(String host, int port)
  4. isServerListening(String host, int port)
  5. isServerListening(String host, int port)
  6. isServing(String host, int port)
  7. isStart(String host, int port)
  8. isStart0(String host, int port)
  9. issueHttpRequest(String methodName, int[] rc, String host, String port, String path)