apache + tomcat 负载均衡模式下 getLocalAddr() 为null的解决办法

[url]http://www.51lingguang.com/?p=504[/url]

在apache + tomcat 负载均衡模式下,通过request.getLocalAddr()无法获取服务器端的ip地址,返回值为null的问题,查找了下,百度里没有有价值的回答,到官方网站上查找了下,说是:

The AJP protocol only passes the web server host name and port. It does not pass the IP address. Therefore, getLocalName() will return whatever is passed via AJP but getLocalAddr() will always return null.

Whilst getLocalAddr() could be modified to return the IP address Tomcat is listening on for AJP connections, I don’t like the inconsistency that would generate when compared to getLocalName() and getLocalPort().

因为AJP的转换,让java端获取不到服务器的ip地址,可以使用以下办法来获取服务器端的ip地址:

String currentIp = InetAddress.getByName(request.getServerName()).getHostAddress();

[color=red]这个一直是获得负载服务器的IP[/color]

先通过request.getServerName()获取到访问域名,然后通过InetAddress.getByName(String serverName)解析到ip地址,但格式是 域名/ip 的形式,再通过getHostAddress()获取到ip地址。

实际上如果需要通过域名解析到ip,也可以通过这个函数来获取:
InetAddress.getByName(域名).getHostAddress()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值