package com.beem.project.beem.utils;

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

/**
 * Utility class to get a free port.
 * @author nikita
 */
public final class FreePort {

    /**
     * Private default constructor.
     */
    private FreePort() {
    }

    /**
     * return a free port.
     * @return free socket port.
     */
    public static int getFreePort() {
	ServerSocket ss;
	int freePort = 0;

	for (int i = 0; i < 10; i++) {
	    freePort = (int) (10000 + Math.round(Math.random() * 10000));
	    try {
		ss = new ServerSocket(freePort);
		freePort = ss.getLocalPort();
		ss.close();
		return freePort;
	    } catch (IOException e) {
		e.printStackTrace();
	    }
	}
	try {
	    ss = new ServerSocket(0);
	    freePort = ss.getLocalPort();
	    ss.close();
	} catch (IOException e) {
	    e.printStackTrace();
	}
	return freePort;
    }
}
