/**
* 获取访问者IP。
* 在一般情况下使用 Request.getRemoteAddr() 即可,但是经过 nginx 等反向代理软件后,这个方法会失效。
*/
private String getIpAddress(HttpServletRequest request) {
// 1. 从 Header 中获取 X-Real-IP
String ip = request.getHeader("X-Real-IP");
if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
return ip;
}
// 2. 从 X-Forwarded-For 获得第一个 IP
ip = request.getHeader("X-Forwarded-For");
if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
// 多次反向代理后会有多个 IP 值,第一个为真实 IP。
int index = ip.indexOf(',');
if (index != -1) {
return ip.substring(0, index);
}
else {
return ip;
}
}
// 3. 调用 getRemoteAddr()
return request.getRemoteAddr();
}
If the project is deployed in the machine, accessed via localhost, get ip address in java may appear ip will be 0: 0: 0: 0: 0: 0: 0: 1.
0: 0: 0: 0: 0: 0: 0: 1 is the manifestation of ipv6, ipv4 equivalent corresponding to 127.0.0.1, which is the machine.
Logically, it should be 127.0.0.1 fishes, why the value obtained is ipv6 format?
In linux system /etc/hosts
file, just comment out the file of ::1 localhost
this line to solve the problem.
$ open /etc/hosts