背景
在进行JavaWeb开发时,通过会记录日志,在记录日志的时候,就会存在客户端的ip存储,那么如何获取客户端对应的ip呢?
知识点
客户端的访问ip,是可以通过Request对象来获取,代码如下,也是我在项目中经常使用到的工具类。
public class IPUtils { /** * 获取IP地址 * @param request * @return */ public static String getIpAddress(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); System.out.println("x-forwarded-for ip: " + ip); if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) { // 多次反向代理后会有多个ip值,第一个ip才是真实ip if( ip.indexOf(",")!=-1 ){ ip = ip.split(",")[0]; } } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); System.out.println("Proxy-Client-IP ip: " + ip); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); System.out.println("WL-Proxy-Client-IP ip: " + ip); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); System.out.println("HTTP_CLIENT_IP ip: " + ip); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); System.out.println("HTTP_X_FORWARDED_FOR ip: " + ip); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("X-Real-IP"); System.out.println("X-Real-IP ip: " + ip); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); System.out.println("getRemoteAddr ip: " + ip); } System.out.println("获取客户端ip: " + ip); return ip; } }
可以通过调用此工具类来获取到当前客户端访问的IP地址了。
特殊情况
其实这里面也存在一些特殊的情况,客户端可能通过代理的方式进行调用后端代码,所以这里的ip其实可能并不是真实的地址。
还有就是如果通过转发的话,ip的获取也可能会有所差异。
所以大家在使用获取ip的情况下,还是不要太过依赖于他。