当前位置:   article > 正文

springboot获取ip地址方法

springboot获取ip地址

需要添加不同情况判断

  1. public static String getIpAddr(HttpServletRequest request) {
  2. String ipAddress = null;
  3. try {
  4. ipAddress = request.getHeader("x-forwarded-for");
  5. if (ipAddress == null || ipAddress.length() == 0
  6. || "unknown".equalsIgnoreCase(ipAddress)) {
  7. ipAddress = request.getHeader("Proxy-Client-IP");
  8. }
  9. if (ipAddress == null || ipAddress.length() == 0
  10. || "unknown".equalsIgnoreCase(ipAddress)) {
  11. ipAddress = request.getHeader("WL-Proxy-Client-IP");
  12. }
  13. if (ipAddress == null || ipAddress.length() == 0
  14. || "unknown".equalsIgnoreCase(ipAddress)) {
  15. ipAddress = request.getRemoteAddr();
  16. if (ipAddress.equals("127.0.0.1")) {
  17. // 根据网卡取本机配置的IP
  18. InetAddress inet = null;
  19. try {
  20. inet = InetAddress.getLocalHost();
  21. } catch (UnknownHostException e) {
  22. e.printStackTrace();
  23. }
  24. ipAddress = inet.getHostAddress();
  25. }
  26. }
  27. // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
  28. if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
  29. // = 15
  30. if (ipAddress.indexOf(",") > 0) {
  31. ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
  32. }
  33. }
  34. } catch (Exception e) {
  35. ipAddress = "";
  36. }
  37. // ipAddress = this.getRequest().getRemoteAddr();
  38. return ipAddress;
  39. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/405387
推荐阅读
相关标签
  

闽ICP备14008679号