Rest - how get IP address of caller

56,873

Solution 1

I think you can get the IP through the request object.

If I'm not mistaken, request.getRemoteAddr() or so.

Solution 2

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();
   // header name is case insensitive
   String xForwardedForIP = req.getHeader("X-Forwarded-For");
   
   //Also if security is enabled
   Principal principal = context.getUserPrincipal();
   String userName = principal.getName();

}

As @Hemant Nagpal mentions, you can also check the X-Forwarded-For header to determine the real source if a load balancer inserts this into the request. According to this answer, the getHeader() call is case insensitive.

Solution 3

You could do something like this:

@WebService
public class YourService {

   @Resource
   WebServiceContext webServiceContext; 

   @WebMethod 
   public String myMethod() { 

      MessageContext messageContext = webServiceContext.getMessageContext();
      HttpServletRequest request = (HttpServletRequest) messageContext.get(MessageContext.SERVLET_REQUEST); 
      String callerIpAddress = request.getRemoteAddr();

      System.out.println("Caller IP = " + callerIpAddress); 

   }
}

Solution 4

Assuming you are making your "web service" with servlets, the rather simple method call .getRemoteAddr() on the request object will give you the callers IP address.

Share:
56,873
Wanderer
Author by

Wanderer

whatever...

Updated on September 20, 2021

Comments

  • Wanderer
    Wanderer over 2 years

    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.