开发者

How can I get the client IP in a JSR168 Portlet?

How can I get the IP of the Client (request) in a JSR168 Portlet?

I'm on Lifera开发者_StackOverflow中文版y 5.2.3

I can get the IP with Liferay internal functionality:

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

Is there any portal neutral way to do this?


Well, one way...if in your Portlet you use Spring MVC, you would have access to the same servlet request and could get the client IP. I don't have the code handy, but if you tack on to your controller class the use of the ActionRequest or the HTTPservlet request. That should get it for you in a non-Liferay fashion.


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);


Sorry, I'm not going to answer your question here, but add some reasons why you might not want to get that IP-Address. For some setups it's common, that requests from one client come through multiple IP-addresses: Either they might be behind a loadbalancer, bundling some connections that have different external IP-addresses, or they might hide behind a proxy farm, where each proxy comes with different addresses.

Also, with a proxy or with NAT involved, you might get multiple clients from the same IP-address.

Therefor: Please take extreme care if you use the client address for authentication purposes: You might need multiple addresses for one client or have multiple clients from one address. Also, you can have multiple clients from (the same) multiple addresses. I've seen many dangerous assumptions regarding the client addresses.

Take care!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜