HttpServletRequest获取ip

fun HttpServletRequest.ip(): String {
    val unknown = "unknown"
    val keyList = arrayOf(
            "X-real-ip",            // nginx自定义配置
            "x-forwarded-for",
            "Proxy-Client-IP",
            "WL-Proxy-Client-IP",
            "HTTP_CLIENT_IP",
            "HTTP_X_FORWARDED_FOR"
    )
    var ip: String? = null
    for(key in keyList) {
        ip = this.getHeader(key)
        if (ip.isNullOrEmpty() || unknown.equals(ip, ignoreCase =  true)) {
            continue
        } else {
            break
        }
    }
    if (ip.isNullOrEmpty() || unknown.equals(ip, ignoreCase =  true)) {
        ip = this.remoteAddr
    }
    if (ip.isNullOrEmpty()) {
        return ""
    }
    // 如果是多级代理,那么取第一个ip为客户端ip
    if (ip.contains(",")){
        ip = ip.substring(0, ip.indexOf(",")).trim()
    }
    return ip
}

你可能感兴趣的:(HttpServletRequest获取ip)