开头鄙视一些人,反复抄袭别人的代码,关键还不能用,害我试了好久,可恶~~
麻烦转载或者盗用的时候,自己先试下
Java代码部分:
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* @Author: feige
* @Date: Created in 15:25 2019/6/15
* @Description:
*/
public class IpUtil {
public static String getIpAddr(HttpServletRequest request) {
String ipAddress = null;
try {
ipAddress = request.getHeader("x-forwarded-for");
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
if (ipAddress.equals("127.0.0.1")) {
// 根据网卡取本机配置的IP
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
ipAddress = inet.getHostAddress();
}
}
// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
// = 15
if (ipAddress.indexOf(",") > 0) {
ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
}
}
} catch (Exception e) {
ipAddress="";
}
return ipAddress;
}
}
重头戏来了:
这个时候如果通过接口调用是能获取到客户的真实ip的
但是如果是通过前端代码去调,势必会走Nginx,这个时候获取的开始是Nginx的本地ip。所以需要配置,这里网上很多坑货的配置真的都不能用啊
应该是这样配置:
location ^~ /api {
proxy_pass http://127.0.0.1:80/;
proxy_read_timeout 90;
#得到请求真实IP
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header HTTP_X_FORWARDED_FOR $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_redirect default;
}
这样就可以了。
如果你还是不行,可能我是你眼里的另外一个坑货。
反正我可以了。