ApiServlet extends HttpServlet { static String getClientAddress(final HttpServletRequest request) { for(final String header : s_clientAddressHeaders) { final String ip = getCorrectIPAddress(request.getHeader(header)); if (ip != null) { return ip; } } return request.getRemoteAddr(); } ApiServlet(); @Override void init(final ServletConfig config); static final Logger s_logger; }
@Test public void getClientAddressWithXForwardedFor() { Mockito.when(request.getHeader(Mockito.eq("X-Forwarded-For"))).thenReturn("192.168.1.1"); Assert.assertEquals("192.168.1.1", ApiServlet.getClientAddress(request)); }
@Test public void getClientAddressWithHttpXForwardedFor() { Mockito.when(request.getHeader(Mockito.eq("HTTP_X_FORWARDED_FOR"))).thenReturn("192.168.1.1"); Assert.assertEquals("192.168.1.1", ApiServlet.getClientAddress(request)); }
@Test public void getClientAddressWithXRemoteAddr() { Mockito.when(request.getHeader(Mockito.eq("Remote_Addr"))).thenReturn("192.168.1.1"); Assert.assertEquals("192.168.1.1", ApiServlet.getClientAddress(request)); }
@Test public void getClientAddressWithHttpClientIp() { Mockito.when(request.getHeader(Mockito.eq("HTTP_CLIENT_IP"))).thenReturn("192.168.1.1"); Assert.assertEquals("192.168.1.1", ApiServlet.getClientAddress(request)); }
@Test public void getClientAddressDefault() { Mockito.when(request.getRemoteAddr()).thenReturn("127.0.0.1"); Assert.assertEquals("127.0.0.1", ApiServlet.getClientAddress(request)); }