Rest - how get IP address of caller

Wanderer picture Wanderer · Sep 29, 2010 · Viewed 51.4k times · Source

I am writing a Java Rest Web Service and need the caller's IP Address. I thought I saw this in the cookie once but now I don't see it. Is there a consistent place to get this information?

I saw one example of using an "OperationalContext" to get it but that was not in java.

Answer

rjdkolb picture rjdkolb · Jun 27, 2011

Inject a HttpServletRequest into your Rest Service as such:

import javax.servlet.http.HttpServletRequest;

@GET
@Path("/yourservice")
@Produces("text/xml")
public String activate(@Context HttpServletRequest requestContext,@Context SecurityContext context){

   String ipAddressRequestCameFrom = requestContext.getRemoteAddr();

   //Also if security is enabled
   Principal principal = context.getUserPrincipal();
   String userName = principal.getName();

}