java获取访间者IP

发布时间:2024年01月19日
package com.example.demo;

import javax.servlet.http.HttpServletRequest;

public class Test {

    /**
     * 获取访间者IP
     * @param request 请求头
     * @return String
     */
    public static String getRemoteHost(HttpServletRequest request) {
        String ip  = request.getHeader("x-forwarded-for");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("Proxy-client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("WL-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)){
            ip = request.getRemoteHost();
        }
        //获取不到值时返回127.0.0.1
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1":ip;
    }
}
文章来源:https://blog.csdn.net/weixin_49990593/article/details/135699325
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。