Java获取真实的IP地址
Posted 大杂烩
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java获取真实的IP地址相关的知识,希望对你有一定的参考价值。
在项目中有时候需要获取访问服务的真实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地址的主要内容,如果未能解决你的问题,请参考以下文章