前言

一般的系统,在正常情况下,都会去获取客户端登录用户的ip地址,当然了,肯定不是拿来做坏事,基本上会用在 异地登录检测,用于城市获取等相关上面,毕竟,违法犯罪的事情我们不做,下面提供一波获取ip地址的工具类

第一种方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
    /**
* 获取客户端ip地址
* @param request
* @return
*/
protected String getIP(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip != null) {
ip = ip.split("\\,")[0];
}
if (!checkIP(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (!checkIP(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (!checkIP(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}

private boolean checkIP(String ip) {
if (ip == null || ip.length() == 0 || "unkown".equalsIgnoreCase(ip)
|| ip.split("\\.").length != 4) {
return false;
}
return true;
}

第二种方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* 获取客户端ip地址
* @param request
* @return
*/
public static String getRealIp(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
System.out.println("x-forwarded-for ip: " + ip);
if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
// 多次反向代理后会有多个ip值,第一个ip才是真实ip
if( ip.indexOf(",")!=-1 ){
ip = ip.split(",")[0];
}
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}

结语

其实,从根本上来说,第一种和第二种没有任何区别,都是一样的,只是写法不一样,至于用哪一种,则主要是看个人喜好……