Java教程

java获取用户IP地址

本文主要是介绍java获取用户IP地址,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

用户Ip地址,先取x_forwarded_for值,不为空则为用户IP,如果为空再取remote_ip的值

public String getIpAddr(HttpServletRequest 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.getRemoteAddr();
        }
        if (!(null == ip || "".equals(ip.trim()) || "null".equalsIgnoreCase(ip.trim())) && ip.contains(",")) {
            ip = ip.split(",")[0];
        }
        return ip;
    }

 

这篇关于java获取用户IP地址的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!