Java擷取用戶端、本機IP__Java

來源:互聯網
上載者:User
擷取用戶端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;    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.