java服务器如何知道客户端请求的ip地址

对于有代理的nginx需要配置一下代理的header:

location / {
          proxy_pass http://127.0.0.1:8080;
        proxy_set_header    Host               $host:$server_port;
        proxy_set_header    Remote_Addr        $remote_addr;
        proxy_set_header    X-Real-IP          $remote_addr;
        proxy_set_header    X-Forwarded-For    $proxy_add_x_forwarded_for;
        proxy_set_header    X-Forwarded-Proto  $scheme;
        proxy_set_header    X-Nginx-Proxy      true;

}

然后在java代码中通过请求HttpServletRequest 来读取ip:

public static String getClientIpAddress(HttpServletRequest request) {
    // 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址
    String headerName = "x-forwarded-for";
    String ip = request.getHeader(headerName);
    if (null != ip && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
        // 多次反向代理后会有多个IP值,第一个IP才是真实IP,它们按照英文逗号','分割
        if (ip.indexOf(",") != -1) {
            ip = ip.split(",")[0];
        }
    }
    if (checkIp(ip)) {
        headerName = "Proxy-Client-IP";
        ip = request.getHeader(headerName);
    }
    if (checkIp(ip)) {
        headerName = "WL-Proxy-Client-IP";
        ip = request.getHeader(headerName);
    }
    if (checkIp(ip)) {
        headerName = "HTTP_CLIENT_IP";
        ip = request.getHeader(headerName);
    }
    if (checkIp(ip)) {
        headerName = "HTTP_X_FORWARDED_FOR";
        ip = request.getHeader(headerName);
    }
    if (checkIp(ip)) {
        headerName = "X-Real-IP";
        ip = request.getHeader(headerName);
    }
    if (checkIp(ip)) {
        headerName = "remote addr";
        ip = request.getRemoteAddr();
        // 127.0.0.1 ipv4, 0:0:0:0:0:0:0:1 ipv6
        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();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            ip = inet.getHostAddress();
        }
    }
    return ip;
}
private static boolean checkIp(String ip) {
    if (null == ip || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        return true;
    }
    return false;
}

你可能感兴趣的:(随笔,服务器,网络)