Here you can find the source of getUnusedPort(int startPort)
Parameter | Description |
---|---|
startPort | suggested port number; ports nearby will be chosen if this is in use |
static int getUnusedPort(int startPort) throws IOException
//package com.java2s; //License from project: LGPL import java.io.IOException; import java.net.ConnectException; import java.net.Socket; public class Main { /**/*from w w w .j ava 2s. c o m*/ * True if spurious java.util.NoSuchElementExceptions should be flagged. * If future JVMs fix this bug, this should be set false or the code * removed. */ public static boolean WARN_ABOUT_NOSUCHELEMENTEXCEPTIONS = true; /** * Returns an unused port number on the local host. * * @param startPort suggested port number; ports nearby will be * chosen if this is in use */ static int getUnusedPort(int startPort) throws IOException { final int nTry = 20; for (int iPort = startPort; iPort < startPort + nTry; iPort++) { try { Socket trySocket = new Socket("localhost", iPort); if (!trySocket.isClosed()) { /* This line causes "java.util.NoSuchElementException" to * be written to System.err, at least at J2SE1.4. * Not my fault! */ if (WARN_ABOUT_NOSUCHELEMENTEXCEPTIONS) { WARN_ABOUT_NOSUCHELEMENTEXCEPTIONS = false; System.err.println( "Please ignore spurious \"" + "java.util.NoSuchElementException\" messages."); } trySocket.close(); } } catch (ConnectException e) { /* Can't connect - this hopefully means that the socket is * unused. */ return iPort; } } throw new IOException("Can't locate an unused port in range " + startPort + " ... " + (startPort + nTry)); } }