擷取用戶端IP 某些情況下需要或取使用者用戶端的ip,用來統計或者攔截,比如有些網站是需要屏蔽海外ip的訪問的,這就需要擷取用戶端的訪問ip。一般情況下用HttpServletRequest對象的getRemoteAddr()方法即可擷取。但是當請求經過HTTP代理或反向 Proxy(如ngrok、nginx等)後這樣擷取ip是不正確的,這有點類似於跳板機。服務經過反向 Proxy後拿到的IP已經不是"第一層"IP了,而是Proxy 伺服器這個"中介"的IP了,有時候甚至存在多級反向 Proxy,那這個時候如何準確的擷取用戶端的IP呢。原來在存在代理的情況下,要求標頭會加上一些特定資訊,如:x-forwarded-for、Proxy-Client-IP、WL-Proxy-Client-IP等來指向ip地址,於是乎擷取ip變得簡單起來。
public static String getIpAddr(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); 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.getRemoteAddr(); } return ip;} 存在多級代理時,則取第一個非 unknown 的IP
public static String getIpAddrAdvanced(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); 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.getRemoteAddr(); } if (ip != null && ip.indexOf(",") != -1) { String[] ipWithMultiProxy = ip.split(","); for(int i = 0; i < ipWithMultiProxy.length; ++i) { String eachIpSegement = ipWithMultiProxy[i]; if (!"unknown".equalsIgnoreCase(eachIpSegement)) { ip = eachIpSegement; break; } } } return ip; }擷取本機IP
這個有什麼應用情境呢。舉個栗子,分布式應用環境中,為了保證定時任務只在單台伺服器上跑,可在定時任務的邏輯中加上ip的判斷(伺服器,比如說公網linux的ip是已知的),來決定哪些伺服器上可以跑定時任務(當然,這種情境也可以使用zookeeper用戶端Curator實現或者分布式鎖實現)
public String getLocalIP() throws Exception { try { InetAddress candidateAddress = null; for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements(); ) { NetworkInterface iface = (NetworkInterface) ifaces.nextElement(); for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements(); ) { InetAddress inetAddr = (InetAddress) inetAddrs.nextElement(); if (!inetAddr.isLoopbackAddress()) { if (inetAddr.isSiteLocalAddress()) { return inetAddr.getHostAddress(); } else if (candidateAddress == null) { candidateAddress = inetAddr; } } } } if (candidateAddress != null) { return candidateAddress.getHostAddress(); } InetAddress jdkSuppliedAddress = InetAddress.getLocalHost(); return jdkSuppliedAddress.getHostAddress(); } catch (Exception e) { e.printStackTrace(); } return null; }