Java如何获取发送请求的电脑的IP地址
作者:inexaustible
文章介绍了如何通过HttpServletRequest获取客户端IP地址,特别是当客户端通过代理访问时,如何使用x-forwarded-for头来获取真实的IP地址
介绍
客户端所有的请求信息都可以通过HttpServletRequest获得,获取客户端ip可以通过getRemoteAddr()获取。
但是如果客户端是通过代理访问我们的服务器,那么getRemoteAddr()获取到的ip就很有可能不是真实的ip,这时候我们可以通过请求头里的x-forwarded-for来获取真实的ip,请求每经一次代理,都会在后面拼接该代理的ip,以逗号分隔。
方法一
此方法获取真实IP(本机IP并不是127.0.0.1)
获取发送请求的电脑的IP地址,并返回
package com.lc.z.common.utils; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import javax.servlet.http.HttpServletRequest; public class IpUtil { /** * 获取请求的ip */ public static String getRequestIp() { RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); // 从获取RequestAttributes中获取HttpServletRequest的信息 HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_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; } }
方法二
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest(); String clientIP = ServletUtil.getClientIP(request); // 本地的服务输出 IP:127.0.0.1 System.out.println("IP:"+ clientIP);
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。