Code example for ServerSocket

Methods: close, getLocalPort

0
public class SocketUtil { 
   
  public static int getFreePort() { 
    int result;
    try { 
      ServerSocket socket = new ServerSocket( 0 );
      result = socket.getLocalPort();
      socket.close();
    } catch( IOException ioe ) {
      throw new RuntimeException( "Failed to find free port.", ioe );
    }  
    return result;
  } 
   
  private SocketUtil() { 
    // prevent instantiation 
  } 
}