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