一、通过HttpServletRequest获取客户端IP地址
在Java中,可以通过HttpServletRequest获取客户端的IP地址。下面展示一个示例代码:
public String getRemoteIp(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
上述代码中的getRemoteIp()方法可以通过HttpServletRequest对象获取客户端的IP地址。在实现过程中,先尝试从Header中获取,并且将多个代理的IP地址以逗号分隔了。
二、通过InetAddress获取客户端IP地址
InetAddress是Java语言中专门用来操作IP地址的类,通过它可以获取本机的IP地址,也可以获取远程主机的IP地址。但是,获取客户端的IP地址时,需要在请求头中获取,因此需要使用HttpServletRequest对象进行获取。下面是一个示例代码:
public String getRemoteIp(HttpServletRequest request) {
String remoteAddr = "";
if (request != null) {
remoteAddr = request.getHeader("X-FORWARDED-FOR");
if (remoteAddr == null || "".equals(remoteAddr)) {
remoteAddr = request.getRemoteAddr();
}
}
return remoteAddr;
}
上述代码中的getRemoteIp()方法是通过HttpServletRequest对象获取客户端的IP地址。如果客户端是通过代理进入的网站或者API,那么X-FORWARDED-FOR的值就是客户端的真实IP地址,否则就是客户端的代理端IP地址。
三、通过过滤器获取客户端IP地址
当多个API都需要获取客户端的IP地址时,可以使用过滤器Filter进行获取。下面是一个示例代码:
public class RemoteIpFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// do nothing
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
String remoteAddr = request.getHeader("X-FORWARDED-FOR");
if (remoteAddr == null || "".equals(remoteAddr)) {
remoteAddr = request.getRemoteAddr();
}
filterChain.doFilter(new RemoteIpWrapper(request, remoteAddr), servletResponse);
}
@Override
public void destroy() {
// do nothing
}
}
上述代码中展示的是通过过滤器(Filter)进行获取。首先使用HttpServletRequest对象获取客户端的IP地址,并且将获取到的值放入自定义的RemoteIpWrapper对象中。这里的RemoteIpWrapper类是一个自定义的HttpServletRequestWrapper类型对象。
四、总结
通过HttpServletRequest、InetAddress和Filter等方法都可以获取客户端的IP地址,但是在实际场景中需要根据实际要求选择。此外,还需要注意一些代理的情况,以便获取到客户端的真实IP地址。