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.
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.
Determining IP Address using $_SERVER Variable Method : There is another way to get the IP Address by using the $_SERVER['REMOTE_ADDR'] or $_SERVER['REMOTE_HOST'] variables. The variable in the $_SERVER array is created by the web server such as apache and those can be used in PHP.
The answer is to use $_SERVER variable. For example, $_SERVER["REMOTE_ADDR"] would return the client's IP address.
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"); // 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With