Get client and login IP (Java)

 In JSP, the method to obtain the client's IP address is: request.getRemoteAddr(), which is effective in most cases. However, after passing through Apache, Nagix and other reverse proxy software, the real IP address of the client cannot be obtained. If reverse proxy software is used, the IP address obtained by the request.getRemoteAddr() method is: 127.0.0.1 or 192.168.1.110, not the real IP of the client.

      After passing through the proxy, because an intermediate layer is added between the client and the service, the server cannot directly obtain the client's IP, and the server-side application cannot directly return the address to the client through the forwarding request. However, the X-FORWARDED-FOR information is added to the HTTP header information of the forwarding request. Used to track the original client IP address and the server address requested by the original client.

public class GetIp {
  public static String getIpAddr(HttpServletRequest request){
    String ipAddress = request.getHeader("x-forwarded-for");
    if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
      ipAddress = request.getHeader("Proxy-Client-IP");
    }
    if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
      ipAddress = request.getHeader("WL-Proxy-Client-IP");
    }
    if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
      ipAddress = request.getRemoteAddr();
      if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){
        //According to the network card to get the IP of the local configuration
        InetAddress inet=null;
        try {
          inet = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
          e.printStackTrace();
        }
      ipAddress= inet.getHostAddress();
      }
    }
    / /For the case of passing through multiple proxies, the first IP is the real IP of the client, and multiple IPs are divided according to ','
    if(ipAddress!=null && ipAddress.length()>15){ //"***. ***.***.***".length() = 15
      if(ipAddress.indexOf(",")>0){
        ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
      }
    }
    return ipAddress;
  }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326147495&siteId=291194637