package com.fkzy.warn.common.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class ServletUtils {

    /**
     * 获取当前线程正在处理的请求对象的 客户端ip
     */
  public static String getRemoteIp() {
      RequestAttributes reqAttr = RequestContextHolder.getRequestAttributes();
      if (reqAttr == null) {
          return null;
      }
      HttpServletRequest request = ((ServletRequestAttributes) reqAttr).getRequest();
      String forwardIp = request.getHeader("x-forwarded-for");

      if (StringUtils.isNotBlank(forwardIp)) {
        // 多个反向代理应用服务系统会用 "," 分隔，取第一个就是客户端的 ip
        // 如: 171.214.183.158, 172.23.22.42, 172.23.22.43
        String[] proxies = forwardIp.split(",");
        if (proxies.length > 0) {
          return proxies[0].trim();
        }
      }
      return request.getRemoteAddr();
  }

}
