首页 > 代码库 > Java获取真实的IP地址
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地址
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。