How can I get the client's IP address in the JSR168 portlet?

How can I get the client (request) IP address in the JSR168 portlet?

I am on Liferay 5.2.3

I can get an IP with Liferay internal functionality:

String ip = com.liferay.portal.util.PortalUtil.getHttpServletRequest(renderRequest).getRemoteAddr();

      

Is there any portal neutral way to do this?

+2


a source to share


3 answers


Well, one way ... if you are using Spring MVC in your portlet, you will have access to the same servlet request and can get the client IP address. I don't have any convenient code, but if you apply your controller class to use ActionRequest or HTTPservlet. This should get it for you non-Liferey.



+1


a source


java.lang.reflect.Field f = request.getClass().getDeclaredField("_request ");
f.setAccessible(true) ;//make visiable
HttpServletRequest httpServletRequest = (HttpServletRequest) f.get(request); get Request

String ip = httpServletRequest.getHeader("x-forwarded-for");
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    ip = httpServletRequest.getHeader("Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    ip = httpServletRequest.getHeader("WL-Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    ip = httpServletRequest.getRemoteAddr();
}
System.out.println("ip:="+ip);

      



+1


a source


Sorry, I'm not going to answer your question here, but add some reasons why you might not want to get this IP. For some settings, it is common for requests from one client to come through multiple IP addresses: either they can be behind the balancer, linking some connections to different external IP addresses, or they can be hidden behind a proxy farm, where each proxy is comes with different addresses.

Also, by using a proxy or using NAT, you can get multiple clients from the same IP address.

To do this: be extremely careful if you are using a client address for authentication purposes: you may need multiple addresses for one client, or have multiple clients from the same address. Alternatively, you can have multiple clients from (the same) multiple addresses. I have seen many dangerous assumptions about customer addresses.

Be careful!

-1


a source







All Articles