How to check for unrestricted Internet access? (captive portal detection)

前端 未结 6 1017
时光说笑
时光说笑 2020-12-04 09:13

I need to reliably detect if a device has full internet access, i.e. that the user is not confined to a captive portal (also called walled garden), i.e. a

6条回答
  •  鱼传尺愫
    2020-12-04 09:56

    This has been implemented on Android 4.2.2+ version - I find their approach fast and interesting :

    CaptivePortalTracker.java detects walled garden as follows - Try to connect to www.google.com/generate_204 - Check that the HTTP response is 204

    If the check fails, we are in a walled garden.

    private boolean isCaptivePortal(InetAddress server) {
        HttpURLConnection urlConnection = null;
        if (!mIsCaptivePortalCheckEnabled) return false;
    
        mUrl = "http://" + server.getHostAddress() + "/generate_204";
        if (DBG) log("Checking " + mUrl);
        try {
            URL url = new URL(mUrl);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setInstanceFollowRedirects(false);
            urlConnection.setConnectTimeout(SOCKET_TIMEOUT_MS);
            urlConnection.setReadTimeout(SOCKET_TIMEOUT_MS);
            urlConnection.setUseCaches(false);
            urlConnection.getInputStream();
            // we got a valid response, but not from the real google
            return urlConnection.getResponseCode() != 204;
        } catch (IOException e) {
            if (DBG) log("Probably not a portal: exception " + e);
            return false;
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
    }
    

提交回复
热议问题