Java HTTP Port Find available(int port)

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

Description

Checks to see if a specific port is available(Bind is not called).

License

Open Source License

Parameter

Parameter Description
port the port number to check for availability

Return

true if the port is available, or false if not

Declaration

public static boolean available(int port) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

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

public class Main {
    /**// w  ww  .  j  a v a2s .c  o m
     * Checks to see if a specific port is available(Bind is not called). setReuseAddress has been enabled to have port
     * reusability in case of TIME_WAIT.
     * 
     * @param port the port number to check for availability
     * @return <tt>true</tt> if the port is available, or <tt>false</tt> if not
     */
    public static boolean available(int port) {
        ServerSocket ss = null;
        DatagramSocket ds = null;
        try {
            ss = new ServerSocket(port);
            ss.setReuseAddress(true);
            ds = new DatagramSocket(port);
            ds.setReuseAddress(true);
            return true;
        } catch (IOException e) {
            // Do nothing
        } finally {
            if (ds != null) {
                ds.close();
            }

            if (ss != null) {
                try {
                    ss.close();
                } catch (IOException e) {
                    /* should not be thrown */
                }
            }
        }

        return false;
    }
}

Related

  1. available(final int port)
  2. available(int port)
  3. available(int port)
  4. available(int port)
  5. available_port()
  6. availableAndReturn(int MIN_PORT_NUMBER, int MAX_PORT_NUMBER)
  7. availablePort()
  8. availablePort(int port)