Java HTTP Port Find getAvailablePort()

Here you can find the source of getAvailablePort()

Description

Getting a available port on range 60000:61000

License

Apache License

Declaration

public static int getAvailablePort() 

Method Source Code

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

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

import java.util.Random;

public class Main {
    /**//from w w w .ja  v a2 s .  co  m
     * Getting a available port on range 60000:61000
     * @return
     */
    public static int getAvailablePort() {
        int initialP = 60000;
        int finalP = 61000;
        for (int i = initialP; i < finalP; i++) {
            int port = new Random().nextInt(finalP - initialP) + initialP;
            ServerSocket ss = null;
            DatagramSocket ds = null;
            try {
                ss = new ServerSocket(port);
                ss.setReuseAddress(true);
                ds = new DatagramSocket(port);
                ds.setReuseAddress(true);
                return port;
            } catch (IOException e) {
            } finally {
                if (ds != null) {
                    ds.close();
                }
                if (ss != null) {
                    try {
                        ss.close();
                    } catch (IOException e) {
                        /* should not be thrown */
                    }
                }
            }
        }
        return -1;
    }
}

Related

  1. getAnonymousPort()
  2. getAvailableListenPort()
  3. getAvailablePort()
  4. getAvailablePort()
  5. getAvailablePort()
  6. getAvailablePort()
  7. getAvailablePort()
  8. getAvailablePort()
  9. getAvailablePort()