IpUtils.java 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package net.chenlin.dp.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 ZhouChenglin
  10. * @email yczclcn@163.com
  11. * @url www.chenlintech.com
  12. * @date 2017年8月8日 下午12:02:56
  13. */
  14. public class IpUtils {
  15. private static Logger LOG = LoggerFactory.getLogger(IpUtils.class);
  16. /**
  17. * 获取IP地址
  18. *
  19. * 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
  20. * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
  21. */
  22. public static String getIpAddr(HttpServletRequest request) {
  23. String ip = null, unknown = "unknown", seperator = ",";
  24. int maxLength = 15;
  25. try {
  26. ip = request.getHeader("x-forwarded-for");
  27. if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) {
  28. ip = request.getHeader("Proxy-Client-IP");
  29. }
  30. if (StringUtils.isEmpty(ip) || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
  31. ip = request.getHeader("WL-Proxy-Client-IP");
  32. }
  33. if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) {
  34. ip = request.getHeader("HTTP_CLIENT_IP");
  35. }
  36. if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) {
  37. ip = request.getHeader("HTTP_X_FORWARDED_FOR");
  38. }
  39. if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) {
  40. ip = request.getRemoteAddr();
  41. }
  42. } catch (Exception e) {
  43. LOG.error("IpUtils ERROR ", e);
  44. }
  45. // 使用代理,则获取第一个IP地址
  46. if (StringUtils.isEmpty(ip) && ip.length() > maxLength) {
  47. int idx = ip.indexOf(seperator);
  48. if (idx > 0) {
  49. ip = ip.substring(0, idx);
  50. }
  51. }
  52. return ip;
  53. }
  54. /**
  55. * 获取ip地址
  56. * @return
  57. */
  58. public static String getIpAddr() {
  59. HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
  60. return getIpAddr(request);
  61. }
  62. }