IPUtils.java 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package com.izouma.nineth.utils;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.springframework.util.StringUtils;
  4. import javax.servlet.http.HttpServletRequest;
  5. import java.net.InetAddress;
  6. import java.net.UnknownHostException;
  7. @Slf4j
  8. public class IPUtils {
  9. private static final String IP_UTILS_FLAG = ",";
  10. private static final String UNKNOWN = "unknown";
  11. private static final String LOCALHOST_IP = "0:0:0:0:0:0:0:1";
  12. private static final String LOCALHOST_IP1 = "127.0.0.1";
  13. /**
  14. * 获取IP地址
  15. * <p>
  16. * 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
  17. * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
  18. */
  19. public static String getIpAddr(HttpServletRequest request) {
  20. String ip = null;
  21. try {
  22. //以下两个获取在k8s中,将真实的客户端IP,放到了x-Original-Forwarded-For。而将WAF的回源地址放到了 x-Forwarded-For了。
  23. ip = request.getHeader("X-Original-Forwarded-For");
  24. if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
  25. ip = request.getHeader("X-Forwarded-For");
  26. }
  27. //获取nginx等代理的ip
  28. if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
  29. ip = request.getHeader("x-forwarded-for");
  30. }
  31. if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
  32. ip = request.getHeader("Proxy-Client-IP");
  33. }
  34. if (StringUtils.isEmpty(ip) || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
  35. ip = request.getHeader("WL-Proxy-Client-IP");
  36. }
  37. if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
  38. ip = request.getHeader("HTTP_CLIENT_IP");
  39. }
  40. if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
  41. ip = request.getHeader("HTTP_X_FORWARDED_FOR");
  42. }
  43. //兼容k8s集群获取ip
  44. if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
  45. ip = request.getRemoteAddr();
  46. if (LOCALHOST_IP1.equalsIgnoreCase(ip) || LOCALHOST_IP.equalsIgnoreCase(ip)) {
  47. //根据网卡取本机配置的IP
  48. InetAddress iNet = null;
  49. try {
  50. iNet = InetAddress.getLocalHost();
  51. ip = iNet.getHostAddress();
  52. } catch (UnknownHostException e) {
  53. log.error("getClientIp error", e);
  54. }
  55. }
  56. }
  57. } catch (Exception e) {
  58. log.error("IPUtils ERROR ", e);
  59. }
  60. //使用代理,则获取第一个IP地址
  61. if (!StringUtils.isEmpty(ip) && ip.indexOf(IP_UTILS_FLAG) > 0) {
  62. ip = ip.substring(0, ip.indexOf(IP_UTILS_FLAG));
  63. }
  64. return ip;
  65. }
  66. }