How to check internet connection in an app

hi there.
i have tried this solution. although it works superb on the PC. from some reason on mobile device it doesn’t. the device thinks it is offline.
i have checked and found that the IP address process doesn’t work and returns an empty IP address.
any ideas why this fails?

the device connected to the same wifi as the PC…

Hi!, I’ll check this solution on my mobile app this week, if I come with the same issue or solution I’ll let you know

That works fine but end up freezing whole game untill connection is made.
Summary : Making www call is correct but not efficient as per my knowledge and experience.

WWW can (and should) be used in a asynchronous manner, making it not freeze the game.

1 Like

Sorry, I’m not super sure how that would be done. My current script is:

public void CheckInternetConnection()
    {
        StartCoroutine(CheckRoutine());
    }


    IEnumerator CheckRoutine()
    {
        UnityWebRequest request = new UnityWebRequest("https://www.google.com/");
        yield return request.SendWebRequest();

        if (string.IsNullOrEmpty(request.error))
        {
            yesNo.text = "Yes";
        }
        else
        {
            yesNo.text = "No";
        }
    }

This is just to test to make sure it works. In the real game I will kill the application if there is an error. Are you saying this is going to freeze the game? Also, something I am super confused about. Am I going to have to check for internet connection at interval or will creating a singleton suffice. As in if I use this method to check in the start method of my menu manager. Once connection is successful will they be able to go offline and continue playing because the game is no longer checking for internet?

EDIT: Another workaround I’ve been wondering is, instead of checking for internet could I just use the ads initialization to kill the application if it fails. I feel like that way I defeat any workarounds because it will always check for internet on it’s own.

Very Simple and Clean
Thanks!!!

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