title: How to get remote HTTP Port number in spring servlet?
body: <p>I need to extract client's IP and port number when he makes a request to the servlet.</p>
  
  <p>Here's my controller code: </p>
  
  <pre><code>@Controller
  public class IpCheckerController {
  
  String ip;
  @ResponseBody
  @RequestMapping(value = "/ipchecker", method = RequestMethod.GET)
  public String get(HttpServletRequest request, HttpServletResponse response) throws IOException {
      for (String header : HEADERS_TO_TRY) {
          ip = request.getHeader(header);
          if (ip != null &amp;&amp; ip.length() != 0 &amp;&amp; !"unknown".equalsIgnoreCase(ip)) {
              return ip + "_"+request.getRemotePort(); // this port is wrong
                                                       // but I left it here for now.
          }
      }
      return request.getRemoteAddr() + "_"+request.getRemotePort();
  }
  
  private static final String[] HEADERS_TO_TRY = { 
      "X-Forwarded-For",
      "Proxy-Client-IP",
      "WL-Proxy-Client-IP",
      "HTTP_X_FORWARDED_FOR",
      "HTTP_X_FORWARDED",
      "HTTP_X_CLUSTER_CLIENT_IP",
      "HTTP_CLIENT_IP",
      "HTTP_FORWARDED_FOR",
      "HTTP_FORWARDED",
      "HTTP_VIA",
      "REMOTE_ADDR" };
  </code></pre>
  
  <p>}</p>
  
  <p>However it is not working as intended. At first I used <code>getRemoteAddr()</code> but it alays returns <code>127.0.0.1</code> or <code>0:0:0:0:0:0:0:1</code>. Then I got this code from someone at work with checking for different headers and now it's working correctly.</p>
  
  <p>However <code>getRemotePort()</code> returns wrong port. My application authentictes users based on ip and port I put into database on login. When someone makes and unauthorised attempt, logger writes down IP and port from which the attemps was made. This port is always different from what <code>getRemotePort()</code> shows. </p>
  
  <p>What headers can I use to get the port just like with the IP? Is there a different way to extract port?</p>
  
  <p>I can't use any extrernal services to parse this data, that's why I have to make my own servlet.</p>