获取ip工具类-IPUtils

今天药忘吃喽~ 2022-12-31 07:30 240阅读 0赞
  1. public class IPUtils {
  2. private static Logger logger = LoggerFactory.getLogger(IPUtils.class);
  3. /** * 获取IP地址 * * 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址 * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址 */
  4. public static String getIpAddr(HttpServletRequest request) {
  5. String ip = null;
  6. try {
  7. ip = request.getHeader("x-forwarded-for");
  8. if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
  9. ip = request.getHeader("Proxy-Client-IP");
  10. }
  11. if (StringUtils.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  12. ip = request.getHeader("WL-Proxy-Client-IP");
  13. }
  14. if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
  15. ip = request.getHeader("HTTP_CLIENT_IP");
  16. }
  17. if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
  18. ip = request.getHeader("HTTP_X_FORWARDED_FOR");
  19. }
  20. if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
  21. ip = request.getRemoteAddr();
  22. }
  23. } catch (Exception e) {
  24. logger.error("IPUtils ERROR ", e);
  25. }
  26. // //使用代理,则获取第一个IP地址
  27. // if(StringUtils.isEmpty(ip) && ip.length() > 15) {
  28. // if(ip.indexOf(",") > 0) {
  29. // ip = ip.substring(0, ip.indexOf(","));
  30. // }
  31. // }
  32. return ip;
  33. }
  34. }

发表评论

表情:
评论列表 (有 0 条评论,240人围观)

还没有评论,来说两句吧...

相关阅读