Java HTTP Port Find isPortAvailable(String hostname, int port)

Here you can find the source of isPortAvailable(String hostname, int port)

Description

Checks to see if a port/hostname combo is available through opening a socked and closing it again

License

Open Source License

Parameter

Parameter Description
hostname the hostname, if null this is bypassed
port the port to check

Return

true if available

Declaration

public static boolean isPortAvailable(String hostname, int port) 

Method Source Code

//package com.java2s;
/*/*from  w w w  . j a  va 2  s  .co  m*/
 *     D3Backend
 *     Copyright (C) 2015  Dries007 & Double Door Development
 *
 *     This program is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU Affero General Public License as published
 *     by the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     This program is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU Affero General Public License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.io.*;

import java.net.InetSocketAddress;
import java.net.ServerSocket;

public class Main {
    /**
     * Checks to see if a port/hostname combo is available through opening a socked and closing it again
     *
     * @param hostname the hostname, if null this is bypassed
     * @param port     the port to check
     * @return true if available
     */
    public static boolean isPortAvailable(String hostname, int port) {
        if (port == -1)
            return false;
        try {
            ServerSocket socket = new ServerSocket();
            socket.bind(hostname == null || hostname.length() == 0 ? new InetSocketAddress(
                    port) : new InetSocketAddress(hostname, port));
            socket.close();
            return true;
        } catch (IOException e) {
            return false;
        }
    }
}

Related

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