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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package com.reyun.saas.mob.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
/**
* Created by nolan on 16/9/22.
* description: IP相关服务类,支持ip地址的获取、地理位置转换.
*/
public class IPAddrUtil {
private static final Logger logger = LoggerFactory.getLogger(IPAddrUtil.class);
static {
String path = "/data/application/mobdna/17monipdb.dat";
IP.load(path);
}
/**
* 根据ip地址转换成对应地理位置
*
* @param httpServletRequest 请求实体
* @return
*/
public static String getLocationFromIpAddr(HttpServletRequest httpServletRequest) {
return getLocationFromIpAddr(getIpAddr(httpServletRequest));
}
/**
* 根据ip地址转换成对应地理位置
*
* @param ipAddr ip地址
* @return
*/
public static String getLocationFromIpAddr(String ipAddr) {
if (ipAddr == null || ipAddr.isEmpty()) {
return "unknown-unknown-unknown";
}
try {
String[] tmp = IP.find(ipAddr);
return String.format("%s-%s-%s", tmp[0], tmp[1], tmp[2]);
} catch (Exception e) {
logger.error("ipAddr:{}", ipAddr);
logger.error("解析ip错误", e);
return "unknown-unknown-unknown";
}
}
/**
* 获取IP地址
*
* @param request 请求实体
* @return
*/
public static String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
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;
}
public static void main(String[] args){
String addr = getLocationFromIpAddr("1.119.176.34");
System.out.println(addr);
}
}