21xrx.com
2024-11-05 19:36:00 Tuesday
登录
文章检索 我的文章 写文章
Java获取请求ip的方法
2023-06-16 11:47:44 深夜i     --     --
Java 获取请求IP ServletRequest HttpServletRequestWrapper WebSocketSession

在进行编程开发时,需要经常获取客户端的请求IP,那么在Java中应该如何获取请求IP呢?下面我们来详细讲解一下。

Java获取请求IP的方法有以下几种:

1.通过ServletRequest对象获取

ServletRequest对象是Java web应用程序中所有请求处理方法的通用接口,其中包含了当前请求的所有信息,通过该对象可以获取请求的IP地址。

代码示例:


import javax.servlet.http.HttpServletRequest;

public class IPUtils {

  public static String getIpAddr(HttpServletRequest request) {

    String ipAddress = request.getHeader("x-forwarded-for");

    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {

      ipAddress = request.getHeader("Proxy-Client-IP");

    }

    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {

      ipAddress = request.getHeader("WL-Proxy-Client-IP");

    }

    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {

      ipAddress = request.getRemoteAddr();

    }

    return ipAddress;

  }

}

2.通过HttpServletRequestWrapper对象获取

HttpServletRequestWrapper是Servlet API提供的一个包装器,可以包装HttpServletRequest对象,并重写相关方法。通过重写getRemoteAddr()方法,就可以获取请求的IP地址了。

代码示例:


import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletRequestWrapper;

public class IPRequestWrapper extends HttpServletRequestWrapper {

  private String ipAddress;

  public IPRequestWrapper(HttpServletRequest request) {

    super(request);

    this.ipAddress = request.getHeader("x-forwarded-for");

    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {

      ipAddress = request.getHeader("Proxy-Client-IP");

    }

    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {

      ipAddress = request.getHeader("WL-Proxy-Client-IP");

    }

    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {

      ipAddress = request.getRemoteAddr();

    }

  }

  @Override

  public String getRemoteAddr()

    return ipAddress;

  

}

使用时只需要在过滤器中将请求对象封装即可。

3.通过WebSocketSession对象获取

在使用WebSocket开发时,可以通过WebSocketSession对象获取请求的IP地址。

代码示例:


import org.springframework.web.socket.WebSocketSession;

public class WebSocketUtils {

  public static String getIpAddr(WebSocketSession session) {

    String ipAddress = session.getRemoteAddress().getHostName();

    return ipAddress;

  }

}

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复
    相似文章