try { ServerSocket server = new ServerSocket(0); System.out.println("This server runs on port " + server.getLocalPort()); } catch (IOException ex) { System.err.println(ex); }