Rest - how get IP address of caller
I think you can get the IP through the request object.
If I'm not mistaken, request.getRemoteAddr()
or so.
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);
}
}
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
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.