IPUtils.java 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /**
  2. * Copyright (c) 2016-2019 人人开源 All rights reserved.
  3. *
  4. * https://www.renren.io
  5. *
  6. * 版权所有,侵权必究!
  7. */
  8. package io.common.utils;
  9. import org.apache.commons.lang.StringUtils;
  10. import org.slf4j.Logger;
  11. import org.slf4j.LoggerFactory;
  12. import javax.servlet.http.HttpServletRequest;
  13. /**
  14. * IP地址
  15. *
  16. * @author Mark sunlightcs@gmail.com
  17. */
  18. public class IPUtils {
  19. private static Logger logger = LoggerFactory.getLogger(IPUtils.class);
  20. /**
  21. * 获取IP地址
  22. *
  23. * 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
  24. * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
  25. */
  26. public static String getIpAddr(HttpServletRequest request) {
  27. String ip = null;
  28. try {
  29. ip = request.getHeader("x-forwarded-for");
  30. if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
  31. ip = request.getHeader("Proxy-Client-IP");
  32. }
  33. if (StringUtils.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  34. ip = request.getHeader("WL-Proxy-Client-IP");
  35. }
  36. if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
  37. ip = request.getHeader("HTTP_CLIENT_IP");
  38. }
  39. if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
  40. ip = request.getHeader("HTTP_X_FORWARDED_FOR");
  41. }
  42. if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
  43. ip = request.getRemoteAddr();
  44. }
  45. } catch (Exception e) {
  46. logger.error("IPUtils ERROR ", e);
  47. }
  48. // //使用代理,则获取第一个IP地址
  49. // if(StringUtils.isEmpty(ip) && ip.length() > 15) {
  50. // if(ip.indexOf(",") > 0) {
  51. // ip = ip.substring(0, ip.indexOf(","));
  52. // }
  53. // }
  54. return ip;
  55. }
  56. }