Java HTTP Port Find isPortAvailable(int port)

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

Description

Checks to see if a specific port is available.

License

Apache License

Parameter

Parameter Description
port the port to check for availability

Declaration

public static boolean isPortAvailable(int port) 

Method Source Code

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

import java.io.IOException;

import java.net.DatagramSocket;

import java.net.ServerSocket;

public class Main {
    private static final int MIN_PORT_NUMBER = 1024;
    private static final int MAX_PORT_NUMBER = 65535;

    /**//w  w w .  ja  va2  s  .c  o  m
     * Checks to see if a specific port is available.
     *
     * @param port the port to check for availability
     */
    public static boolean isPortAvailable(int port) {
        if (port < MIN_PORT_NUMBER || port > MAX_PORT_NUMBER) {
            throw new IllegalArgumentException("Invalid start port: " + 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) {
        } finally {
            if (ds != null) {
                ds.close();
            }

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

        return false;
    }
}

Related

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