代码如下自取:
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
/** * @Title 获取客户端ip地址类 * @Author YangWanJie * @Date 2021/6/30 16:08 * @versioin V1.0 **/
@Slf4j
public class IpUtil {
/** * @Title 获取用户IP地址 * 两种可能性 * 一:客户端未经过代理,直接访问服务器端; * 二:客户端通过多级代理,最终到达服务器端; * @Author YangWanJie * @Date 2020/1/20 10:57 * @versioin V1.0 **/
public static String getIp(HttpServletRequest request) {
// 反向代理时获取真实ip
String ip = request.getHeader("X-Forwarded-For");
if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
// 多次反向代理后会有多个ip值,第一个ip才是真实ip
if (ip.indexOf(",") > 0) {
ip = ip.split(",")[0];
}
}
//Proxy-Client-IP/WL- Proxy-Client-IP :这个一般是经过apache http服务器的请求才会有,用apache http做代理时一般会加上Proxy-Client-IP请求头,而WL-Proxy-Client-IP是他的weblogic插件加上的头。
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");
}
//nginx代理一般会加上此请求头
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
//根据网卡取本机配置的IP
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
ip = inet.getHostAddress();
} catch (UnknownHostException e) {
log.error("x-forwarded-for:{},Proxy-Client-IP:{},WL-Proxy-Client-IP:{},HTTP_CLIENT_IP:{},X-Real-IP:{},错误信息:{}", request.getHeader("X-Forwarded-For"), request.getHeader("Proxy-Client-IP"), request.getHeader("WL-Proxy-Client-IP"), request.getHeader("HTTP_CLIENT_IP"), request.getHeader("X-Real-IP"), e.getMessage());
}
}
}
return ip;
}
}