java request 获取ip地址,如何在Java HttpServletRequest中获取客户端IP地址

"在开发Java Web应用程序时,遇到获取客户端IP地址的难题。尝试了`request.getRemoteAddr()`、`request.getHeader("X-FORWARDED-FOR")`以及`InetAddress.getLocalHost()`,但结果总是返回默认网关地址而非实际客户端IP。寻求解决方案。"
摘要由CSDN通过智能技术生成

I am trying to develop a Java web application (Servlet) which I need to get clients IP address.

Please do not considers this as a duplicate question because I tried all the possible answers that are available in the stackoverflow.

Following is my code so far:

1)

String ipAddress = request.getRemoteAddr();

In this case most of the tome I get the 'Default gateway adress'(147.120.1.5). not my machine ip address(174.120.100.17).

2)

String ipAddress = request.getHeader("X-FORWARDED-FOR");

if (ipAddress == null) {

ipAddress = request.getRemoteAddr();

}

In this case most of the tome I get the 'Default gateway adress'(147.120.1.5). not my machine ip address(174.120.100.17).

3)

InetAddress IP=InetAddress.getLocalHost();

System.out.println(IP.getHostAddress());

In this case I got the server IP Address(147.120.20.1).

My IP address in 147.120.100.17.Now I don't know how to get the real client IP address. Please make an answer.

Thank you very much.

解决方案

Try this one,

String ipAddress = request.getHeader("X-FORWARDED-FOR");

if (ipAddress == null) {

ipAddress = request.getRemoteAddr();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值