IpAddressUtil.java 911 B

12345678910111213141516171819202122232425262728293031323334
  1. package com.iamberry.wechat.tools;
  2. import javax.servlet.http.HttpServletRequest;
  3. /**
  4. * @author:何秀刚
  5. * @description: ip地址工具类
  6. * @createDate:2016年5月26日
  7. */
  8. public class IpAddressUtil {
  9. /**
  10. * 获取ip地址, 若多级代理,第一个IP为客户端真实IP,多个IP按照','分割
  11. * @param request
  12. * @return
  13. */
  14. public static String getIpAddr(HttpServletRequest request) {
  15. String ip = request.getHeader("x-forwarded-for");
  16. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  17. ip = request.getHeader("Proxy-Client-IP");
  18. }
  19. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  20. ip = request.getHeader("WL-Proxy-Client-IP");
  21. }
  22. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  23. ip = request.getRemoteAddr();
  24. }
  25. if (ip != null && ip.indexOf(",") != -1) {
  26. ip = ip.split(",")[0];
  27. }
  28. return ip;
  29. }
  30. }