方式1

直接获取IP。

  1. HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
  2. String ipaddr = request.getRemoteAddr();
  3. if(ipaddr == "0:0:0:0:0:0:0:1"){
  4. ipaddr ="127.0.0.1";
  5. }
  6. System.out.println(ipaddr);

方式2

封装为工具类。

  1. import javax.servlet.http.HttpServletRequest;
  2. public class IPUtil {
  3. /**
  4. * 获取请求IP
  5. * @param request 请求对象
  6. * @return
  7. */
  8. public static String getIpAddress(HttpServletRequest request) {
  9. String ip = request.getHeader("X-Forwarded-For");
  10. if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  11. ip = request.getHeader("X-Real-IP");
  12. }
  13. if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  14. ip = request.getHeader("Proxy-Client-IP");
  15. }
  16. if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  17. ip = request.getHeader("WL-Proxy-Client-IP");
  18. }
  19. if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  20. ip = request.getHeader("HTTP-CLIENT-IP");
  21. }
  22. if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  23. ip = request.getRemoteAddr();
  24. }
  25. String OperationIp = request.getHeader("Operation-IP");
  26. if(OperationIp != null && !"".equals(OperationIp)) {
  27. ip = ip + ";" + OperationIp;
  28. }
  29. return ip;
  30. }
  31. }