IpUtil.java 1.8 KB

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