参考:https://www.jb51.net/article/243543.htm

    1. package com.tj.demo.utils;
    2. import org.apache.commons.lang.StringUtils;
    3. import javax.servlet.http.HttpServletRequest;
    4. public class TjIpUtils {
    5. /***
    6. * 获取客户端ip地址
    7. * @param request
    8. */
    9. public static String getIP(final HttpServletRequest request) throws Exception {
    10. if (request == null) {
    11. throw (new Exception("getIpAddr method HttpServletRequest Object is null"));
    12. }
    13. String ipStr = request.getHeader("x-forwarded-for");
    14. if (StringUtils.isBlank(ipStr) || "unknown".equalsIgnoreCase(ipStr)) {
    15. ipStr = request.getHeader("Proxy-Client-IP");
    16. }
    17. if (StringUtils.isBlank(ipStr) || "unknown".equalsIgnoreCase(ipStr)) {
    18. ipStr = request.getHeader("WL-Proxy-Client-IP");
    19. }
    20. if (StringUtils.isBlank(ipStr) || "unknown".equalsIgnoreCase(ipStr)) {
    21. ipStr = request.getRemoteAddr();
    22. }
    23. // 多个路由时,取第一个非unknown的ip
    24. final String[] arr = ipStr.split(",");
    25. for (final String str : arr) {
    26. if (!"unknown".equalsIgnoreCase(str)) {
    27. ipStr = str;
    28. break;
    29. }
    30. }
    31. //目的是将localhost访问对应的ip 0:0:0:0:0:0:0:1 转成 127.0.0.1。
    32. return ipStr.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ipStr;
    33. }
    34. }