Here you can find the source of getAvailablePort()
public static int getAvailablePort()
//package com.java2s; /*/* w w w . j av a 2 s . com*/ * Copyright 2013 SmartBear Software * * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by the European Commission - subsequent * versions of the EUPL (the "Licence"); * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: * * http://ec.europa.eu/idabc/eupl * * Unless required by applicable law or agreed to in writing, software distributed under the Licence is * distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the Licence for the specific language governing permissions and limitations * under the Licence. */ import java.io.IOException; import java.net.ServerSocket; public class Main { public static int getAvailablePort() { try (ServerSocket ss = new ServerSocket(0)) { ss.setReuseAddress(true); return ss.getLocalPort(); } catch (IOException e) { } finally { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } return -1; } public static int getAvailablePort(int start) { while (!isPortAvailable(start)) start++; return start; } public static boolean isPortAvailable(int port) { try (ServerSocket ss = new ServerSocket(port)) { ss.setReuseAddress(true); return true; } catch (IOException e) { } return false; } }