java httpRequest getRemoteAddr allways return 127.0.0.1

折月煮酒 提交于 2019-12-14 03:48:02

问题


Hello everybody and thanks for your help,

I am developing a web application using JSF and for security reasons i need to capture the user's IP when he does the log in.

I am using the following code:

HttpServletRequest request=(HttpServletRequest) context.getExternalContext().getRequest();
remoteAddress=request.getRemoteAddr();

The thing is that when I check my app logs to check the ip address it always returns 127.0.0.1.

[INFO] 07/01/2014 11:04:22 --> User xxx connected from 127.0.0.1

[INFO] 07/01/2014 11:27:43 --> User xxx connected from 127.0.0.1

For more detail:

  • I am using tomcat 7
  • My server works inside a debian virtual machine
  • I am connecting to the server from a different pc from the one containing the VM.

I have searched in internet and read about using:

request.getHeader("X-FORWARDED-FOR");

But It did not solved my problem.

I am quite lost at the moment, any ideas why is this happening?


回答1:


First of all, check if your http server should be forwarding the headers. You you're using nginx, this should work

proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

If you're already done that, you can accomplish that using Tomcat's RemoteIpValve

<Valve className="org.apache.catalina.valves.RemoteIpValve"
           remoteIpHeader="X-Forwarded-For"
           requestAttributesEnabled="true"
           internalProxies="127.0.0.1"  />

That way, when you call request.getRemoteAddr(), it will be providing the right information.



来源:https://stackoverflow.com/questions/20969513/java-httprequest-getremoteaddr-allways-return-127-0-0-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!