1 public class IpUtils {
2 private static final String[] HEADERS = {
3 "X-Forwarded-For",
4 "Proxy-Client-IP",
5 "WL-Proxy-Client-IP",
6 "HTTP_X_FORWARDED_FOR",
7 "HTTP_X_FORWARDED",
8 "HTTP_X_CLUSTER_CLIENT_IP",
9 "HTTP_CLIENT_IP",
10 "HTTP_FORWARDED_FOR",
11 "HTTP_FORWARDED",
12 "HTTP_VIA",
13 "REMOTE_ADDR",
14 "X-Real-IP"
15 };
16
17 /**
18 * 判断ip是否为空,空返回true
19 * @param ip
20 * @return
21 */
22 public static boolean isEmptyIp(final String ip){
23 return (ip == null || ip.length() == 0 || ip.trim().equals("") || "unknown".equalsIgnoreCase(ip));
24 }
25
26
27 /**
28 * 判断ip是否不为空,不为空返回true
29 * @param ip
30 * @return
31 */
32 public static boolean isNotEmptyIp(final String ip){
33 return !isEmptyIp(ip);
34 }
35
36 /***
37 * 获取客户端ip地址(可以穿透代理)
38 * @param request HttpServletRequest
39 * @return
40 */
41 public static String getIpAddress(HttpServletRequest request) {
42 String ip = "";
43 for (String header : HEADERS) {
44 ip = request.getHeader(header);
45 if(isNotEmptyIp(ip)) {
46 break;
47 }
48 }
49 if(isEmptyIp(ip)){
50 ip = request.getRemoteAddr();
51 }
52 if(isNotEmptyIp(ip) && ip.contains(",")){
53 ip = ip.split(",")[0];
54 }
55 if("0:0:0:0:0:0:0:1".equals(ip)){
56 ip = "127.0.0.1";
57 }
58 return ip;
59 }
60
61
62 /**
63 * 获取本机的局域网ip地址,兼容Linux
64 * @return String
65 * @throws Exception
66 */
67 public String getLocalHostIP() throws Exception{
68 Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
69 String localHostAddress = "";
70 while(allNetInterfaces.hasMoreElements()){
71 NetworkInterface networkInterface = allNetInterfaces.nextElement();
72 Enumeration<InetAddress> address = networkInterface.getInetAddresses();
73 while(address.hasMoreElements()){
74 InetAddress inetAddress = address.nextElement();
75 if(inetAddress != null && inetAddress instanceof Inet4Address){
76 localHostAddress = inetAddress.getHostAddress();
77 }
78 }
79 }
80 return localHostAddress;
81 }
82
83 }