Socket socket = new Socket("localhost", 8080); int localPort = socket.getLocalPort(); System.out.println("Local port number: " + localPort);
ServerSocket serverSocket = new ServerSocket(9000); Socket socket = serverSocket.accept(); int localPort = socket.getLocalPort(); System.out.println("Local port number: " + localPort);In this example, we create a new ServerSocket object on port 9000. We listen for incoming connections using the accept() method, which returns a new Socket object for each incoming connection. We retrieve the local port number of the new Socket object using the getLocalPort() method and print it to the console. The java.net.Socket package library is used for implementing network sockets.