try { ServerSocket serverSocket = new ServerSocket(8080); System.out.println("Server is running on port: " + serverSocket.getLocalPort()); } catch (IOException e) { e.printStackTrace(); }
ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(0); int port = serverSocket.getLocalPort(); System.out.println("Port number assigned: " + port); } catch (IOException e) { e.printStackTrace(); } finally { if (serverSocket != null) { try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } }In this example, we create a ServerSocket object on an unspecified port (0), and then use the getLocalPort() method to get the assigned port number. Finally, we close the serverSocket object.