当前位置:天才代写 > tutorial > JAVA 教程 > JAVA如何获取会见用户的客户端IP(合用于公网与局域网)

JAVA如何获取会见用户的客户端IP(合用于公网与局域网)

2017-11-02 08:00 星期四 所属: JAVA 教程 浏览:533

/** 
 * 获取会见用户的客户端IP(合用于公网与局域网). 
 */
public static final String getIpAddr(final HttpServletRequest request)  
        throws Exception {  
    if (request == null) {  
        throw (new Exception("getIpAddr method HttpServletRequest Object is null"));  
    }  
    String ipString = request.getHeader("x-forwarded-for");  
    if (StringUtils.isBlank(ipString) || "unknown".equalsIgnoreCase(ipString)) {  
        ipString = request.getHeader("Proxy-Client-IP");  
    }  
    if (StringUtils.isBlank(ipString) || "unknown".equalsIgnoreCase(ipString)) {  
        ipString = request.getHeader("WL-Proxy-Client-IP");  
    }  
    if (StringUtils.isBlank(ipString) || "unknown".equalsIgnoreCase(ipString)) {  
        ipString = request.getRemoteAddr();  
    }  
      
    // 多个路由时,取第一个非unknown的ip  
    final String[] arr = ipString.split(",");  
    for (final String str : arr) {  
        if (!"unknown".equalsIgnoreCase(str)) {  
            ipString = str;  
            break;  
        }  
    }  
      
    return ipString;  
}

作者:csdn博客 微wx笑

 

    关键字:

天才代写-代写联系方式