获取ip工具
import lombok.extern.slf4j.slf4j;
import org.apache.commons.lang3.stringutils;
import javax.servlet.http.httpservletrequest;
/**
* ip地址
*
* @date 2020年3月6日 下午12:57:02
*/
@slf4j
public class iputils {
/**
* 获取ip地址
*
* 使用nginx等反向代理软件, 则不能通过request.getremoteaddr()获取ip地址
* 如果使用了多级反向代理的话,x-forwarded-for的值并不止一个,而是一串ip地址,x-forwarded-for中第一个非unknown的有效ip字符串,则为真实ip地址
*/
public static string getipaddr(httpservletrequest request) {
string ip = null;
try {
ip = request.getheader("x-forwarded-for");
if (stringutils.isempty(ip) || "unknown".equalsignorecase(ip)) {
ip = request.getheader("proxy-client-ip");
}
if (stringutils.isempty(ip) || ip.length() == 0 || "unknown".equalsignorecase(ip)) {
ip = request.getheader("wl-proxy-client-ip");
}
if (stringutils.isempty(ip) || "unknown".equalsignorecase(ip)) {
ip = request.getheader("http_client_ip");
}
if (stringutils.isempty(ip) || "unknown".equalsignorecase(ip)) {
ip = request.getheader("http_x_forwarded_for");
}
if (stringutils.isempty(ip) || "unknown".equalsignorecase(ip)) {
ip = request.getremoteaddr();
}
} catch (exception e) {
log.error("iputils error ", e);
}
//使用代理,则获取第一个ip地址
if(stringutils.isempty(ip) && ip.length() > 15) {
if(ip.indexof(",") > 0) {
ip = ip.substring(0, ip.indexof(","));
}
}
return ip;
}
}
如果你使用了nginx 则获取到的ip都会是127.0.0.1
在代理中加入如下配置proxy_set_header x-forwarded-for $remote_addr;
server {
listen 80;
server_name api.qimen.pro;
# 服务器文件上传大小限制
client_max_body_size 10m;
location / {
proxy_pass http://gymserver;
proxy_set_header x-forwarded-for $remote_addr;
}
}
到此这篇关于解决使用了nginx获取ip地址都是127.0.0.1 的问题的文章就介绍到这了,更多相关nginx获取ip地址问题内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!