在使用springboot时,需要获取访问客户端的IP地址,
//获取客户端IP地址
private String getIpAddress() {
String ip = request.getHeader("x-forwarded-for");
if(ip == null || ip.length() == 0 || "unknow".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.getRemoteAddr ();
if (ip.equals ("127.0.0.1")) {
//根据网卡取本机配置的IP
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost ();
} catch (Exception e) {
e.printStackTrace ();
}
ip = inet.getHostAddress ();
}
}
// 多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
if (ip != null && ip.length () > 15) {
if (ip.indexOf (",") > 0) {
ip = ip.substring (0, ip.indexOf (","));
}
}
return ip;
}
在windows7 使用localshot访问时,获取到的IP地址为0:0:0:0:0:1 原因是localhost解析不出来 需要使用正常的IP地址访问时,则可正确的得到访问client端的IP地址
标签:springboot,ip,IP地址,request,length,IP,null,客户端
来源: https://blog.csdn.net/qq116165600/article/details/95460054