码迷,mamicode.com
首页 > 编程语言 > 详细

Java获取真实的IP地址

时间:2016-09-02 18:49:59      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:

在项目中有时候需要获取访问服务的真实ip地址,通过nginx中转后,你获取到的ip地址可能是nginx的ip。如下方法可以获取真实的ip

首先在nginx中要配置:

proxy_set_header X-Real-IP          $remote_addr;
proxy_set_header X-Forwarded-For    $proxy_add_x_forwarded_for;
proxy_set_header Host $host:$server_port;
 proxy_set_header X-Forwarded-Proto "https";
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
public class NetworkUtil {

    private static final String[] HEADERS_TO_TRY = { 
        "X-Forwarded-For",
        "Proxy-Client-IP", 
        "WL-Proxy-Client-IP",
        "HTTP_X_FORWARDED_FOR",
        "HTTP_X_FORWARDED",
        "HTTP_X_CLUSTER_CLIENT_IP",
        "HTTP_CLIENT_IP",
        "HTTP_FORWARDED_FOR",
        "HTTP_FORWARDED",
        "HTTP_VIA",
        "REMOTE_ADDR" 
    };

public static String getRemoteHost(HttpServletRequest request) { for (String header : HEADERS_TO_TRY) { String ip = request.getHeader(header); if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) { return ip; } } return request.getRemoteAddr(); } }

 

Java获取真实的IP地址

标签:

原文地址:http://www.cnblogs.com/ahang/p/5834274.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!