How to check internet connection in an app

Note that Application.internetReachability will only determines if the device has access to either a Carrier Mobile Data (via a SIM card) or a Local Network (WIFI for example) which can return false-positive depending on multiple factors involving the device, its drivers, its OS and more.

In my case, I made it so that use Application.internetReachability initially and, then check up a html request on a webpage I put in my website.

First, I set up an IEnumerator to check things on a frequency I find correct-ish

   private bool CheckTimerIsActive = false;
   private void InternetCheckAccess(bool isActive)
    {
        CheckTimerIsActive = isActive;
        if (CheckTimerIsActive)
        {
            if(TimedContentCheckCoroutine != null)
            {
                StopCoroutine(TimedContentCheckCoroutine);
                TimedContentCheckCoroutine = null;
            }
            TimedContentCheckCoroutine = InternetAccessCheck();
            StartCoroutine(TimedContentCheckCoroutine);
        }
    }

    private IEnumerator TimedContentCheckCoroutine;

    private IEnumerator InternetAccessCheck()
    {
        while (CheckTimerIsActive)
        {
            if(Application.internetReachability != NetworkReachability.NotReachable)
            {
                CheckIfOnline();
                yield return new WaitForSeconds(5f);
            }
            else
            {
                SetInternetAccess(false);
                yield return new WaitForSeconds(10f);
            }
            yield return null;
        }
    }

If the device can be online, it calls the function to look up an HTML request every 5 secs. If it’s cannot be online, it look up every 10 secs instead of 5 secs. This is just so that if the user get back online, I can update the UI to allow access to the online feature again.

Here’s the code for the CheckIfOnline() function:

private string HtmlLookUpResult_Content;
    private char[] HtmlLookUpResult_Chars;
    private StreamReader HtmlLookUpResult_Reader;
    private bool HtmlLookUpResult_isSuccess;
    private HttpWebRequest HtmlLookUpResult_Request;
    private HttpWebResponse HtmlLookUpResult_Response;
    private void CheckIfOnline()
    {
        HtmlLookUpResult_Content = UniversalEnum.String_Empty;
        HtmlLookUpResult_Request = (HttpWebRequest)WebRequest.Create(UniversalEnum.WebHtml_isOnline);
        try
        {
            using (HtmlLookUpResult_Response = (HttpWebResponse)HtmlLookUpResult_Request.GetResponse())
            {
                HtmlLookUpResult_isSuccess = (int)HtmlLookUpResult_Response.StatusCode < 299 && (int)HtmlLookUpResult_Response.StatusCode >= 200;
                if (HtmlLookUpResult_isSuccess)
                {
                    using (HtmlLookUpResult_Reader = new StreamReader(HtmlLookUpResult_Response.GetResponseStream()))
                    {
                        HtmlLookUpResult_Chars = new char[1];
                        HtmlLookUpResult_Reader.Read(HtmlLookUpResult_Chars, 0, 1);
                        HtmlLookUpResult_Content += HtmlLookUpResult_Chars[0];
                    }
                }
            }
        }
        catch
        {
            HtmlLookUpResult_Content = UniversalEnum.String_Empty;
        }

        if (HtmlLookUpResult_Content == UniversalEnum.String_Empty) {
            SetInternetAccess(false);
        }
        else
        {
            SetInternetAccess(true);
        }
    }

This is made in a way that makes sure that the repeated call for the function doesn’t generate any new memory block other than the result from the HTMLWebRequest. It’s Garbage-Collector-Friendly. :wink:
In case some wonder, the UniversalEnum I use above is just a non-monohavior class script in which I set all my persistent and reusable static readonly variables for references. Things like particular color codes, animation Hash, directory paths, etc. If you use the same variable (exact same) multiple times, it’s always better to set the variable and access it instead of generating a new one every time you need it.

If you wonder what’s the UniversalEnum.WebHtml_isOnline goes to, it’s the www link to an html page I placed in a subfolder in my website that contain the text: [1] in its content. No header nor actual web content and the whole files size is 3 bytes. In comparison, a regular website ping is 56 bytes in size. In fact, I could place any text in it and this will still work as long as it’s first character is a recognizable char. After all, I’m only looking for the first character of the website html file to even just exist. No need to compare or check if the content is alright as all I want to know is that I could check the first character from a web page. (Why I placed 3 character is in cases of some sort of firewall or security measure that would stop 1-byte or 2-bytes signals content.)

If I want to force all the players to be offline (not affecting the score board or something for a moment), I just have to change the html file name for something else via Filezilla or CPanel, wait for about 1 minute and by then I know that nobody should have access to the online features.

Lastly, there’s the SetInternetAccess(bool) function I haven’t given yet:

    private bool GameIsOnline = false;
    private void SetInternetAccess(bool isOn)
    {
        if (GameIsOnline != isOn)
        {
            if (isOn)
            {
                //Internet is Active.
                Debug.Log("Enabling Internet related content.");
            }
            else
            {
                //Internet is NOT Active.
                Debug.Log("Disabling Internet related content.");
            }
            GameIsOnline = isOn;
        }
    }

This way, I can change the UI and disable or enable content based on if the device is online or not.

Since HTTP is relatively slow, this is not a system with good usability to determine connectivity with fast-responsive systems like online-shop, but it’s a relatively safe and reliable way of just checking if the user’s client can connect or not to a server or service.

1 Like