title: Retrieve the port of the server on startup of servlet container (independent of server)
body: <p>I want to retreive the host and port of the server my Jersey 2.6 container is running in. The container is currently deployed on a Tomcat 7. However, I am forced to release my application deployable on every server which supports Java servlets. In this case, it's a Tomcat, but the solution must be server independent.</p>
  
  <p>I have registered a Jersey startup class, where I want to fetch the host and port. However, I haven't found any solution to get the port yet.</p>
  
  <p>My class, which is called when my Jersey servlet is initialized:</p>
  
  <pre><code>public class ServletInitialization extends ResourceConfig {
      public ServletInitialization() {
          int port    = ???;
          String host = InetAddress.getLocalHost().getHostName();
      }
  }
  </code></pre>
  
  <p>On my researches, I have found a <a href="https://stackoverflow.com/questions/7481432/i-need-to-know-the-http-and-https-port-my-java-webapp-is-running-on-webapp-start">3 year old question</a>, which refers to the same problem. The accepted answer is focused on a tomcat and I think will only run on a Tomcat correctly (<code>import org.apache.catalina.*</code>). I would like to avoid to modify the server engine, the server configuration nor inject anything into the server on startup.</p>
  
  <p>I have tried to use a plain Java servlet, but can't find a method to fetch the port there, too:</p>
  
  <pre><code>public class ServletInitializationPlain extends HttpServlet {
  
      @Override
      public void init() {
         int port = ???;  
      }   
  }
  </code></pre>
  
  <p>Does someone have idea on how to retrieve the port out of a servlet container on startup (independant from the server it's running in)?</p>
  
  <hr>
  
  <p><strong>EDIT</strong></p>
  
  <p>I have accepted steohans solution, but I think it is quite tricky, why my ServletInitialization is not called on startup of the web container. Because actually ResourceConfig is not a Servlet. I will explain this issue now:</p>
  
  <p>I have extended ResourceConfig.class, which is a subclass of an Application.class. This Application class is not an extended Java servlet, but an own class of Jersey. I though an Application is called on the startup of the web container. However, in the Jersey specification can be read, that the Application class needs to be itself handled by a ServletContainer.class which is a subclass of a Java Servlet.
  This handling is defined in the web.xml.
  And in the end, everything is a servlet here.</p>
  
  <p>As it's not possible to get the port on startup, it's of course possible when a request is dispatched:</p>
  
  <pre><code>@Path("example")
  public class ServletMethods {
      @GET
      public Response example(@HeaderParam("Host") String host) {
           return Response.ok(host).build();
      }
  }
  </code></pre>