zoukankan      html  css  js  c++  java
  • 获取客户端的ip方式

     1 package czc.superzig.modular.utils;
     2 
     3 import javax.servlet.http.HttpServletRequest;
     4 import java.net.InetAddress;
     5 import java.net.UnknownHostException;
     6 
     7 public class IpUtil {
     8     public static String getIpAddr(HttpServletRequest request) {
     9         String ipAddress = null;
    10         try {
    11             ipAddress = request.getHeader("x-forwarded-for");
    12             if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
    13                 ipAddress = request.getHeader("Proxy-Client-IP");
    14             }
    15             if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
    16                 ipAddress = request.getHeader("WL-Proxy-Client-IP");
    17             }
    18             if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
    19                 ipAddress = request.getRemoteAddr();
    20                 if (ipAddress.equals("127.0.0.1")) {
    21                     // 根据网卡取本机配置的IP
    22                     InetAddress inet = null;
    23                     try {
    24                         inet = InetAddress.getLocalHost();
    25                     } catch (UnknownHostException e) {
    26                         e.printStackTrace();
    27                     }
    28                     ipAddress = inet.getHostAddress();
    29                 }
    30             }
    31             // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
    32             if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
    33                 // = 15
    34                 if (ipAddress.indexOf(",") > 0) {
    35                     ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
    36                 }
    37             }
    38         } catch (Exception e) {
    39             ipAddress="";
    40         }
    41         // ipAddress = this.getRequest().getRemoteAddr();
    42 
    43         return ipAddress;
    44     }
    45 }

    由于negix转发可能会重新分配ip地址
    所以negeix中设置

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

  • 相关阅读:
    搭建页面:数据库的增删改查
    阿里云的使用运维安装
    promis:异步编程
    微信开发笔记
    细数那些带打赏功能的平台
    写给自己的TypeScript 入门小纲
    Node.js自学笔记之回调函数
    来简书坚持一个月日更之后
    全选或者单选checkbox的值动态添加到div
    一个前端妹子的悲欢编程之路
  • 原文地址:https://www.cnblogs.com/xiatc/p/13273025.html
Copyright © 2011-2022 走看看