java获取客户端ip

我们知道一个机器对应一个物理ip,如果能获得这个ip,基本就能锁定这个人啦。最近在用Java搭一个博客系统,也可以用到这个。比如记录用户登录,留言评论等,可以把用户的ip写到数据库中去。

具体代码如下

Java

  1. //获得物理ip
  2. public static String getIpAddr(HttpServletRequest request){
  3.     String ipAddress = request.getHeader("x-forwarded-for");
  4.     if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
  5.         ipAddress = request.getHeader("Proxy-Client-IP");
  6.     }
  7.     if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
  8.         ipAddress = request.getHeader("WL-Proxy-Client-IP");
  9.     }
  10.     if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
  11.         ipAddress = request.getRemoteAddr();
  12.         if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){
  13.             //根据网卡取本机配置的IP
  14.             InetAddress inet=null;
  15.             try {
  16.                 inet = InetAddress.getLocalHost();
  17.             } catch (UnknownHostException e) {
  18.                 e.printStackTrace();
  19.             }
  20.             ipAddress= inet.getHostAddress();
  21.         }
  22.     }
  23.     //对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
  24.     if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
  25.         if(ipAddress.indexOf(",")>0){
  26.             ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
  27.         }
  28.     }
  29.     return ipAddress;
  30. }

然后 应用在了添加评论上,添加一条评论,查看数据库。

ip:10.128.222.24

然后查看一下本机的ip,完全一致。


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

半缘修道半缘君丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值