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

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

Description

See if a port is available for listening on by trying connect to it and seeing if that works or fails

License

Apache License

Parameter

Parameter Description
host a parameter
port a parameter

Declaration

public static boolean isPortAvailable(String host, int port) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Main {
    /**//ww w .  j a  v a  2  s . c  o  m
     * See if a port is available for listening on by trying to listen
     * on it and seeing if that works or fails.
     *
     * @param port port to listen to
     * @return true if the port was available for listening on
     */
    public static boolean isPortAvailable(int port) {
        try {
            ServerSocket socket = new ServerSocket(port);
            socket.close();
            return true;
        } catch (IOException e) {
            return false;
        }
    }

    /**
     * See if a port is available for listening on by trying connect to it
     * and seeing if that works or fails
     *
     * @param host
     * @param port
     * @return
     */
    public static boolean isPortAvailable(String host, int port) {
        try {
            Socket socket = new Socket(host, port);
            socket.close();
            return false;
        } catch (IOException e) {
            return true;
        }
    }
}

Related

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