Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to discover embedded Jetty port after requesting random available port?

Tags:

java

jetty

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..

like image 816
Leo Avatar asked Jan 16 '12 18:01

Leo


People also ask

How do I find out what ports are available?

One of the simplest ways to check for open ports is to use NetStat.exe. You can find this tool in the System32 folder on Windows 10. With NetStat, you can see open ports or ports that a specific host uses.

What is the default port for Jetty?

When you install jetty in eclipse, the default port for jetty is 8080. So you need to change it into an XML file.


2 Answers

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.

like image 124
paskos Avatar answered Sep 29 '22 01:09

paskos


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/ 
like image 41
O.Badr Avatar answered Sep 29 '22 01:09

O.Badr