Rest – how get IP address of caller

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 req,@Context SecurityContext context){

   String ipAddressRequestCameFrom = requestContext.getRemoteAddr();
   // header name is case insensitive
   String xForwardedForIP = req.getHeader("X-Forwarded-For");

   // if xForwardedForIP is populated use it, else return ipAddressRequestCameFrom 
   String ip = xForwardedForIP != null ? xForwardedForIP : ipAddressRequestCameFrom;
   System.out.println("IP is "+ip);


   // get the host name the client contacted. If the header `Host` is populated the `Host` header is automatically returned.
   // An AWS ALB populated the Host header for you.
   String hostNameRequestCameFrom = req.getServerName();
   System.out.println("Host is "+hostNameRequestCameFrom);

   
   //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.

You can also get the servername that the client contacted. This is either the DNS name or the value set in the Host header with an OSI layer 7 load balancer can populate.

1. Example: no headers are populated

curl "http://127.0.0.1:8080/"

returns

IP is 127.0.0.1
Host is 127.0.0.1

2. Example: X-Forwarded-For and Host headers are populated

curl --header "X-Forwarded-For: 1.2.3.4" --header "Host: bla.bla.com:8443" "http://127.0.0.1:8080/"

returns

IP is 1.2.3.4
Host is bla.bla.com

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)