IPUtils.java 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package io.renren.common.utils;
  2. import com.alibaba.druid.util.StringUtils;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import javax.servlet.http.HttpServletRequest;
  6. /**
  7. * IP地址
  8. *
  9. * @author chenshun
  10. * @email sunlightcs@gmail.com
  11. * @date 2017年3月8日 下午12:57:02
  12. */
  13. public class IPUtils {
  14. private static Logger logger = LoggerFactory.getLogger(IPUtils.class);
  15. /**
  16. * 获取IP地址
  17. *
  18. * 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
  19. * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
  20. */
  21. public static String getIpAddr(HttpServletRequest request) {
  22. String ip = null;
  23. try {
  24. ip = request.getHeader("x-forwarded-for");
  25. if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
  26. ip = request.getHeader("Proxy-Client-IP");
  27. }
  28. if (StringUtils.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  29. ip = request.getHeader("WL-Proxy-Client-IP");
  30. }
  31. if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
  32. ip = request.getHeader("HTTP_CLIENT_IP");
  33. }
  34. if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
  35. ip = request.getHeader("HTTP_X_FORWARDED_FOR");
  36. }
  37. if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
  38. ip = request.getRemoteAddr();
  39. }
  40. } catch (Exception e) {
  41. logger.error("IPUtils ERROR ", e);
  42. }
  43. // //使用代理,则获取第一个IP地址
  44. // if(StringUtils.isEmpty(ip) && ip.length() > 15) {
  45. // if(ip.indexOf(",") > 0) {
  46. // ip = ip.substring(0, ip.indexOf(","));
  47. // }
  48. // }
  49. return ip;
  50. }
  51. }