How to discover embedded Jetty port after requesting random available port?
Solution 1
The function getPort()
returns the configured value.
Try server.getConnectors()[0].getLocalPort()
it should return the selected port.
For Jetty 9:
You need to use ((ServerConnector)server.getConnectors()[0]).getLocalPort()
.
In both cases: you need to call server.start()
first.
Solution 2
In addition to @pascos answer, you can also get the seleted port by:
server.getURI().getPort(); // e.g: 44759
If you are interested to get the whole server URL (with port), you can do:
server.getURI().toString(); // e.g: http://127.0.0.1:44759/
Leo
Computer Scientist, Entrepreneur, Father of two & Java enthusiast. Trying to build a better world through programming.
Updated on July 07, 2022Comments
-
Leo almost 2 years
Server server = new Server(0); (..) server.start(); // this returns _zero_ ?!?! int listeningPort = server.getConnectors()[0].getPort();
I'm using embedded Jetty 7 API. Passing zero to the Server(int) constructor cause Jetty to assign an available port automatically, how can i discover which port was assigned?
I have read the docs, but cannot find this info.
thanks..