HttpServletRequest.getRemoteAddr()之代理提交

有很多应用需要取得来访者的IP地址,比如防止未授权用户或恶意用户的访问等。J2EE的SERVLET标准接口javax.servlet.http.HttpServletRequest提供了getRemoteAddr()方法,用来取得来访者的IP地址。

request.getRemoteAddr()这种方法在大部分情况下获得的IP都是有效的。但是在客户通过向代理软件就不能获取到客户端的真实IP地址了。经过代理以后,由于在客户端和服务之间增加了中间层,因此服务器无法直接拿到客户端的IP,服务器端应用也无法直接通过转发请求的地址返回给客户端。但是在转发请求的HTTP头信息中,增加了X-FORWARDED-FOR信息用以跟踪原有的客户端IP地址和原来客户端请求的服务器地址。所以想要获得客户端的真正IP就要先判断一下request.getHead();

Java获取客户端的IP代码为:

复制代码
复制代码
 1 public String getAddr(HttpServletRequest request){
 2 
 3     String ip=request.getHeader("x-forwarded-for");
 4        if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)){
 5          ip=request.getHeader("Proxy-Client-IP");
 6        }
 7         if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)){
 8          ip=request.getHeader("WL-Proxy-Client-IP");
 9        }
10        if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)){
11          ip=request.getRemoteAddr();
12        }
13 
14      return ip;
15 
16 }
复制代码
复制代码
posted @   silentmuh  阅读(552)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
Live2D
欢迎阅读『HttpServletRequest.getRemoteAddr()之代理提交』
  1. 1 Walk Thru Fire Vicetone
  2. 2 爱你 王心凌
  3. 3 Inspire Capo Productions - Serenity
  4. 4 Welcome Home Radical Face
  5. 5 粉红色的回忆 李玲玉
Welcome Home - Radical Face
00:00 / 00:00
An audio error has occurred, player will skip forward in 2 seconds.

作词 : Ben P. Cooper

作曲 : Cooper

Sleep don't visit, so I choke on sun

And the days blur into one

And the backs of my eyes hum with things I've never done

Sheets are swaying from an old clothesline

Was never much but we've made the most

Welcome home

Ships are launching from my chest

Some have names but most do not

If you find one,please let me know what piece I've lost

Heal the scars from off my back

I don't need them anymore

You can throw them out or keep them in your mason jars

I've come home

All my nightmares escaped my head

Bar the door, please don't let them in

You were never supposed to leave

Now my head's splitting at the seams

And I don't know if I can

Here, beneath my lungs

I feel your thumbs press into my skin again

点击右上角即可分享
微信分享提示