Search Unity

How to check internet connection in an app

Discussion in 'Scripting' started by sunartoryan, Feb 7, 2016.

  1. sunartoryan

    sunartoryan

    Joined:
    Feb 7, 2016
    Posts:
    5
    Hello all.
    I just a newbie in the programming Unity. And I here have a trouble.

    I have an app, and I want this app when running in Android/iOS platform, this app is connected to internet. If the internet connection is off, this app show a dialogue box : "Please connect to internet" & disabling all features or cannot run, until it connected to internet.

    Please help me to create the C# script in unity. And where I place this script? in gameObject or else..?

    Thank you very much.
     
  2. domkia

    domkia

    Joined:
    Aug 19, 2012
    Posts:
    99
  3. Lishin

    Lishin

    Joined:
    Jun 11, 2016
    Posts:
    1
    Code (CSharp):
    1.  if(Application.internetReachability == NetworkReachability.NotReachable)
    2.         {
    3.             Debug.Log("Error. Check internet connection!");
    4.         }
     
  4. wildDevelop

    wildDevelop

    Joined:
    Oct 9, 2016
    Posts:
    2
    Best answer , clean and easy.
     
  5. Piflik

    Piflik

    Joined:
    Sep 11, 2011
    Posts:
    293
    And wrong. You don't use this to check if you actually can reach the internet, but to distinguish between WiFi and Carrier networks.
     
  6. User340

    User340

    Joined:
    Feb 28, 2007
    Posts:
    3,001
    I would just make a simple WWW call to some webpage. If it returns success, you have internet, if it returns an error, you don't.
     
  7. Mazyod

    Mazyod

    Joined:
    Apr 21, 2014
    Posts:
    25
    If you need 100% reachability check, it's not a matter of the user being connected to "a" network. It's a matter of the user being able to reach a certain service that you should carefully pick.

    Personally, I opt-in for a simple endpoint on my servers that the users try to reach, and if that succeeds, I can guarantee they can use my game services.

    One of the many cases they might be connected to a network but can't reach your services are captive networks and intranets.
     
    Bunny83, Sheroo, creepteks and 5 others like this.
  8. elenzil

    elenzil

    Joined:
    Jan 23, 2014
    Posts:
    73
    This does not seem quite right. Application.internetReachability returns a NetworkReachability enum, which has three values: WiFi/Wired, Cellular, and None. So you can use this to detect say "you have no carrier and no wifi".

    The other comments here that you probably want to also ping some low-cost endpoint on whatever server/s you're interested in still hold true, for the reasons other folks have mentioned.
     
    DBarlok and WILEz1975 like this.
  9. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    I'd verify you can actually connect to your specific game service rather than a generic internet connection check. Users may be attached to a public wifi that requires a webpage sign in, where some services are allowed without sign in but others are blocked. Firewalls on public or private corporate wifi may block certain ports that may be important to you, but let through traffic you would use for a generic internet check. Really only checking the connection to your actual game service is the closest thing to a guarantee.
     
  10. ovirta

    ovirta

    Joined:
    Mar 20, 2015
    Posts:
    42
    I agree. You can definitely test whether network is present with Application.internetReachability. Additionally pinging endpoint will verify data transfer capability.
     
    Last edited: Sep 7, 2017
    DBarlok likes this.
  11. Hoorza

    Hoorza

    Joined:
    May 8, 2016
    Posts:
    45
  12. tbigham

    tbigham

    Joined:
    Mar 6, 2017
    Posts:
    1
    How would you interpret the case where Application.internetReachability returns NetworkReachability.NotReachable?
     
    DBarlok and ovirta like this.
  13. DBarlok

    DBarlok

    Joined:
    Apr 24, 2013
    Posts:
    268
    Years later but...Sounds cool. In my case im using Photon, so i will go to check the game has... data transfer capability.

    if (!PhotonNetwork.connected)
    {
    // do something
    }
     
    Hoorza likes this.
  14. AlexCarrington

    AlexCarrington

    Joined:
    Apr 9, 2015
    Posts:
    21
    If your game/app uses Google Play Games you can simply pause at the splash screen and wait for a google signin to continue playing.
     
    goldcloud144 likes this.
  15. joshcamas

    joshcamas

    Joined:
    Jun 16, 2017
    Posts:
    1,278
    Just ping google.com, since it's pretty much guaranteed to be up :)
     
  16. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    You'll get false negative results on corporate networks which sometimes are configured to block ICMP packets from passing through the firewall. The network I wrote this message on for example.
     
    ksf000 likes this.
  17. jfa257

    jfa257

    Joined:
    Jul 17, 2013
    Posts:
    9
    I think some people are misreading the documentation. They tell you not to use to check internet availability IF the devices are handheld. If not, this works perfect since the wifi/lan internet option is true or false when NetworkReachability.ReachableViaLocalAreaNetwork. is checked. I think it would work still on handhelds, since the hotspot has to create some sort of network using the tethered device as a router. Maybe the refer to the innacuracy of the class to properly detect if there is internet feed on a handheld connected to a hotspot network. In any case, if the connection is strong enough, it will get detected, if not, although present for email or other apps, don't think would be of much use for multiplayer connectivity though, so it's a moot point if the NetworkReachability class can accurate see if a handheld is receiving internet or not.
     
  18. stack86

    stack86

    Joined:
    Jul 22, 2016
    Posts:
    11
    Thanks!

    This was perfect for my scenario, where I simply wanted to detect that the users phone was in airplane mode so I could just disable all the networking altogether.

    As people have pointed out you still need to check connectivity when online ,but this is very useful to know with absolute certainty that you don't even need to try looking for connectivity because you'e offline.
     
    kacvinsky likes this.
  19. garrido86

    garrido86

    Joined:
    Dec 17, 2013
    Posts:
    233
    If you don't have your own Ressource to check against, you can Ping as a fallback 8.8.8.8 which is googles server and unless your user is behind a state run firewall or a zombie outbreak, it's safe bet to determine for internet availability.
     
    Discipol and joshcamas like this.
  20. joshcamas

    joshcamas

    Joined:
    Jun 16, 2017
    Posts:
    1,278
    what if I want my app to work during a zombie outbreak in china :(
     
    Kechy likes this.
  21. kenan238

    kenan238

    Joined:
    Mar 7, 2020
    Posts:
    3
    joshcamas sry but i did a script for the photon gameserver if u are connected or no
    1-Create a UI text and write:Your are connected to internet and photon gameservers
    and create a script and paste this :
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;

    public class InternetConnection : MonoBehaviour
    {
    public Text changingText;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }

    public void TextChange()
    {
    if (PhotonNetwork.connected)
    {
    changingText.text = "Your are connected to internet and photon gameservers";
    }

    if (Application.internetReachability == NetworkReachability.NotReachable)
    {
    changingText.text = "Your notare connected to internet and photon gameservers. Please check your internet connection!";
    }
    }
    }

    And drag the script in your player game object
    Is it usefull?
     
  22. joshcamas

    joshcamas

    Joined:
    Jun 16, 2017
    Posts:
    1,278
    Looks perfect, my friend
     
  23. KEric

    KEric

    Joined:
    Jan 11, 2013
    Posts:
    62
    I've created an Android's library that can be used as Unity's plugin for this purpose. If anyone's interested it's available under https://github.com/rixment/awu-plugin
    Hope it helps, cheers!
     
    Last edited: Mar 17, 2020
    creepteks and AcidFz like this.
  24. elliotfriesen

    elliotfriesen

    Joined:
    Mar 17, 2020
    Posts:
    71
    Hi, I am trying to make an app where it displays a message on your phone if only cellular is on and not WiFi because I’ve had this problem in the past and I cannot figure out how to trigger the message. I’ve made many games and I have tried to search for an answer but I cant find one. All it is, is just checking if only cellular is on and not WiFi. If someone would answer it would be great
     
  25. codemaker2015

    codemaker2015

    Joined:
    Aug 19, 2018
    Posts:
    27

    1. Code (CSharp):
      1. if(Application.internetReachability == NetworkReachability.NotReachable)
      2.         {
      3.             Debug.Log("Error. Check internet connection!");
      4.         }
     
    aquilis007 and DhiaSendi like this.
  26. Margallo

    Margallo

    Joined:
    May 1, 2016
    Posts:
    9
    Hi! I know this thread is old but i want to ask something.If i use photon just to know my game has connected to internet. is it limited to 20 users? I will not make a multiplayer i just want to check my game has data transfer capability. Thanks.
     
  27. DBarlok

    DBarlok

    Joined:
    Apr 24, 2013
    Posts:
    268
    No, in single player you will not be limited, Photon just checks your user profile when you log in to the Server
    with the id or something and limits based on that.

    In your case i will use something more performant:
    https://forum.unity.com/threads/how-to-check-internet-connection-in-an-app.384541/
     
  28. CPlusSharp22

    CPlusSharp22

    Joined:
    Dec 1, 2012
    Posts:
    111
    marck_ozz likes this.
  29. AcidFz

    AcidFz

    Joined:
    Jul 26, 2020
    Posts:
    12
    So has anyone actually checked for internet connection?

    What is the simple way to check for internet?

    Its almost Oct.2020 anyone?

    So If internet available do this, else do this.

    Thanks, non coder
     
  30. unknownsk

    unknownsk

    Joined:
    Jan 16, 2020
    Posts:
    36
    i am still trying to find out. lol. no one knows answer
     
  31. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    I would just test internet how you plan on using it, because access to the Internet doesn't guarantee access to whatever service you need. For example, if you will use Internet access to talk to a PHP front end for a database, just test it by sending a trivial http request to the same server. YMMV
     
    JeffDUnity3D likes this.
  32. Havokki

    Havokki

    Joined:
    Jun 28, 2015
    Posts:
    118
    Haven't people answered this already?

    If you need internet connection, you are most likely going to use it for something, so just ping the service you need. Or if you just want to check connection, ping one or more large services that are most likely going to be available (like Google for example).
     
    AcidFz likes this.
  33. AcidFz

    AcidFz

    Joined:
    Jul 26, 2020
    Posts:
    12
    I think we are waiting for some nice coder to type an example code : :)

    "Dont delete" its a valid reply. Haha.

    But ping is alright. You have to ping where you are getting the file or something.
     
  34. marck_ozz

    marck_ozz

    Joined:
    Nov 30, 2018
    Posts:
    107
    Hello all!!!!

    This is my Approach to this topic. I hope it helps to somebody:

    I tried this over ethernet connection, WiFi, and VPN with good and expected results

    In general, I use a Ping method to check if the are internet connection but first I use "Application.internetReachability" to ckeck if there are connection at all or not

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5. using System;
    6. //using System.Web;
    7. //using System.Net.NetworkInformation;
    8.  
    9. public class YourAppScript : MonoBehaviour
    10. {
    11.     private string linkURL;
    12.     public void CheckConnection()
    13.     {
    14.         string m_ReachabilityText = "";
    15.      
    16.         //Check if the device cannot reach the internet at all (that means if the "cable", "WiFi", etc. is connected or not)
    17.         //if not, don't waste your time.
    18.         if (Application.internetReachability == NetworkReachability.NotReachable)
    19.         {
    20.             m_ReachabilityText = "Not Connected.";
    21.             Debug.Log("Internet : " + m_ReachabilityText);
    22.         }
    23.         else
    24.         {
    25.             StartCoroutine(DoPing()); //It could be a network connection but not internet access so you have to ping your host/server to be sure.
    26.         }
    27.     }
    28.  
    29.     IEnumerator DoPing()
    30.     {
    31.         Debug.Log("Do Ping");
    32.         TestPing.DoPing();
    33.         yield return new WaitUntil(() => TestPing.isDone);
    34.         connected = TestPing.status;
    35.  
    36.         if (connected)
    37.         {
    38.             Debug.Log("Connected");
    39.             //Do your thing once the connection is confirmed
    40.             Debug.Log(TestPing.ipAdd); // just to be sure if that is your IP
    41.         }
    42.         else
    43.         {
    44.             //if negative result awarn your user
    45.             //and do your thing with this result
    46.             Debug.Log(TestPing.ipAdd);
    47.             Debug.Log("Please check your network connections or network permissions");
    48.         }
    49.     }
    50. }
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. //using System.Net.NetworkInformation; NetworkInformation.Ping & UnityEngine.Ping have a conflict and I need Debug.Log so I commented this line
    5. using System.Net;
    6. using System;
    7. using System.IO;
    8.  
    9. public static class TestPing
    10. {
    11.     public static bool status = false;
    12.     public static bool isDone = false;
    13.     public static string ipAdd; //The IP addres for the ping call
    14.  
    15.     public static bool PingThis()
    16.     {
    17.         try
    18.         {
    19.             //I strongly recommend to check Ping, Ping.Send & PingOptions on microsoft C# docu or other C# info source
    20.             //in this block you configure the ping call to your host or server in order to check if there is network connection.
    21.          
    22.             //from https://stackoverflow.com/questions/55461884/how-to-ping-for-ipv4-only
    23.             //from https://stackoverflow.com/questions/49069381/why-ping-timeout-is-not-working-correctly
    24.             //and from https://stackoverflow.com/questions/2031824/what-is-the-best-way-to-check-for-internet-connectivity-using-net
    25.          
    26.          
    27.             System.Net.NetworkInformation.Ping myPing = new System.Net.NetworkInformation.Ping();
    28.          
    29.             byte[] buffer = new byte[32]; //array that contains data to be sent with the ICMP echo
    30.             int timeout = 10000; //in milliseconds
    31.             System.Net.NetworkInformation.PingOptions pingOptions = new System.Net.NetworkInformation.PingOptions(64, true);
    32.             System.Net.NetworkInformation.PingReply reply = myPing.Send(ipAdd, timeout, buffer, pingOptions); //the same method can be used without the timeout, data buffer & pingOptions overloadd but this works for me
    33.             if (reply.Status == System.Net.NetworkInformation.IPStatus.Success)
    34.             {
    35.                 return true;
    36.             }
    37.             else if(reply.Status == System.Net.NetworkInformation.IPStatus.TimedOut) //to handle the timeout scenario
    38.             {
    39.                 return status;
    40.             }
    41.             else
    42.             {
    43.                 return false;
    44.             }
    45.         }
    46.         catch (Exception e) //To catch any exception of the method
    47.         {
    48.             Debug.Log(e);
    49.             return false;
    50.         }
    51.         finally { } //To not get stuck in an error or exception, see "Try, Catch, Finally" docs.
    52.     }
    53.  
    54.     public static string GetIPAddress() //Get the actual IP addres of your host/server
    55.     {
    56.         //Yes, I could use the "host name" or the "host IP address" direct on the ping.send method BUT!!
    57.         //I find out and "Situation" in which due to my network setting in my PC any ping call (from script or cmd console)
    58.         //returned the IPv6 instead of IPv4 which couse the Ping.Send thrown an exception
    59.         //that could be the scenario for many of your users so you have to ensure this run for everyone.
    60.      
    61.      
    62.         //from https://stackoverflow.com/questions/1059526/get-ipv4-addresses-from-dns-gethostentry
    63.      
    64.         IPHostEntry host;
    65.         host = Dns.GetHostEntry("google.com"); //I use google.com as an example but it can be any host name (preferably yours)
    66.  
    67.         try
    68.         {
    69.             host = Dns.GetHostEntry("google.com"); //Get the IP host entry from your host/server
    70.         }
    71.         catch (Exception e)
    72.         {
    73.             Debug.Log(e);
    74.         }
    75.         finally { }
    76.  
    77.  
    78.         foreach (IPAddress ip in host.AddressList)
    79.         {
    80.             if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) //filter just the IPv4 IPs
    81.             {                                                                      //you can play around with this and get all the IP arrays (if any)
    82.                 return ip.ToString();                                              //and check the connection with all of then if needed
    83.             }
    84.         }
    85.         return string.Empty;
    86.     }
    87.  
    88.     public static void DoPing()
    89.     {
    90.         ipAdd = GetIPAddress(); //call to get the IP address from your host/server
    91.  
    92.         if (PingThis()) //call to check if you can make ping to that host IP
    93.         {
    94.             status = true;
    95.             isDone = true;
    96.         }
    97.         else
    98.         {
    99.             status = false;
    100.             isDone = true;
    101.         }
    102.     }
    103. }
    I think It could be some scenarios in which this method could not work such as firewalls exceptions, weird networks setting, corporate networks and so on, but for the MOST of the user this should works.


    If you see something wrong in the code or have any question, please let me know.

    Saludos!!!
     
  35. CrandellWS

    CrandellWS

    Joined:
    Oct 31, 2015
    Posts:
    178
    how would i check if the device has it's own IPv4 IP so I might do a client /server for offline play?

    Also how could i have them auto find each other?

    Thanks for any help...
     
  36. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Finding each other is usually done through your own dedicated server, or through a cloud service (which is really just a dedicated server operated by someone else). If you meant finding each other on a local network, Unet had their Network Discovery feature. Mirror might have carried it over as well. But I remember constant reliability complaints regarding network discovery. You could look into how it works under the hood though, or if Mirror has it still and you're using Mirror well there you go, try that.

    Doing direct IP connections is a more reliable method, though requires some basic knowledge of the player hosting the game to find their own IP address. But it has the advantage of also being useful over the Internet, for players who also know how to enable port forwarding on their router.

    How you would check your own IP address in code should probably be done with whatever network API you are using, but here is a rather generic C# method to do so which probably works. Note that a network interface can have multiple IP addresses assigned, which is why I would instead check using your chosen network API.

    Get IP Address Using C# Code (c-sharpcorner.com)
     
  37. CrandellWS

    CrandellWS

    Joined:
    Oct 31, 2015
    Posts:
    178
    Joe-Censored likes this.
  38. lazybitkings

    lazybitkings

    Joined:
    Oct 30, 2019
    Posts:
    4
    If I ping www.google.com, will users in china (behind the great firewall) get an accurate response to whether internet is available or not?
     
  39. makaka-org

    makaka-org

    Joined:
    Dec 1, 2013
    Posts:
    1,026
    You can check true status of Internet Connection with Internet Reachability Verifier.
    Unity API by default can't provide true status unfortunately.

     
    LilGames likes this.
  40. vinimaykaul

    vinimaykaul

    Joined:
    Jun 16, 2020
    Posts:
    6
    Thanks you So Much... Such an easy solution ... Worked for me.
     
  41. shacharoz

    shacharoz

    Joined:
    Jul 11, 2013
    Posts:
    98

    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...
     
  42. marck_ozz

    marck_ozz

    Joined:
    Nov 30, 2018
    Posts:
    107
    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
     
  43. aayan06pk

    aayan06pk

    Joined:
    Aug 28, 2021
    Posts:
    1
    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.
     
  44. joshcamas

    joshcamas

    Joined:
    Jun 16, 2017
    Posts:
    1,278
    WWW can (and should) be used in a asynchronous manner, making it not freeze the game.
     
    Bunny83 likes this.
  45. da_egg5

    da_egg5

    Joined:
    Nov 20, 2021
    Posts:
    8
    Sorry, I'm not super sure how that would be done. My current script is:

    Code (CSharp):
    1. public void CheckInternetConnection()
    2.     {
    3.         StartCoroutine(CheckRoutine());
    4.     }
    5.  
    6.  
    7.     IEnumerator CheckRoutine()
    8.     {
    9.         UnityWebRequest request = new UnityWebRequest("https://www.google.com/");
    10.         yield return request.SendWebRequest();
    11.  
    12.         if (string.IsNullOrEmpty(request.error))
    13.         {
    14.             yesNo.text = "Yes";
    15.         }
    16.         else
    17.         {
    18.             yesNo.text = "No";
    19.         }
    20.     }
    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.
     
    Last edited: May 12, 2022
  46. Rachan

    Rachan

    Joined:
    Dec 3, 2012
    Posts:
    783
    Very Simple and Clean
    Thanks!!!
     
  47. Max_Bol

    Max_Bol

    Joined:
    May 12, 2014
    Posts:
    168
    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

    Code (CSharp):
    1.  
    2.    private bool CheckTimerIsActive = false;
    3.    private void InternetCheckAccess(bool isActive)
    4.     {
    5.         CheckTimerIsActive = isActive;
    6.         if (CheckTimerIsActive)
    7.         {
    8.             if(TimedContentCheckCoroutine != null)
    9.             {
    10.                 StopCoroutine(TimedContentCheckCoroutine);
    11.                 TimedContentCheckCoroutine = null;
    12.             }
    13.             TimedContentCheckCoroutine = InternetAccessCheck();
    14.             StartCoroutine(TimedContentCheckCoroutine);
    15.         }
    16.     }
    17.  
    18.     private IEnumerator TimedContentCheckCoroutine;
    19.  
    20.     private IEnumerator InternetAccessCheck()
    21.     {
    22.         while (CheckTimerIsActive)
    23.         {
    24.             if(Application.internetReachability != NetworkReachability.NotReachable)
    25.             {
    26.                 CheckIfOnline();
    27.                 yield return new WaitForSeconds(5f);
    28.             }
    29.             else
    30.             {
    31.                 SetInternetAccess(false);
    32.                 yield return new WaitForSeconds(10f);
    33.             }
    34.             yield return null;
    35.         }
    36.     }
    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:

    Code (CSharp):
    1. private string HtmlLookUpResult_Content;
    2.     private char[] HtmlLookUpResult_Chars;
    3.     private StreamReader HtmlLookUpResult_Reader;
    4.     private bool HtmlLookUpResult_isSuccess;
    5.     private HttpWebRequest HtmlLookUpResult_Request;
    6.     private HttpWebResponse HtmlLookUpResult_Response;
    7.     private void CheckIfOnline()
    8.     {
    9.         HtmlLookUpResult_Content = UniversalEnum.String_Empty;
    10.         HtmlLookUpResult_Request = (HttpWebRequest)WebRequest.Create(UniversalEnum.WebHtml_isOnline);
    11.         try
    12.         {
    13.             using (HtmlLookUpResult_Response = (HttpWebResponse)HtmlLookUpResult_Request.GetResponse())
    14.             {
    15.                 HtmlLookUpResult_isSuccess = (int)HtmlLookUpResult_Response.StatusCode < 299 && (int)HtmlLookUpResult_Response.StatusCode >= 200;
    16.                 if (HtmlLookUpResult_isSuccess)
    17.                 {
    18.                     using (HtmlLookUpResult_Reader = new StreamReader(HtmlLookUpResult_Response.GetResponseStream()))
    19.                     {
    20.                         HtmlLookUpResult_Chars = new char[1];
    21.                         HtmlLookUpResult_Reader.Read(HtmlLookUpResult_Chars, 0, 1);
    22.                         HtmlLookUpResult_Content += HtmlLookUpResult_Chars[0];
    23.                     }
    24.                 }
    25.             }
    26.         }
    27.         catch
    28.         {
    29.             HtmlLookUpResult_Content = UniversalEnum.String_Empty;
    30.         }
    31.  
    32.         if (HtmlLookUpResult_Content == UniversalEnum.String_Empty) {
    33.             SetInternetAccess(false);
    34.         }
    35.         else
    36.         {
    37.             SetInternetAccess(true);
    38.         }
    39.     }
    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. ;)
    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:

    Code (CSharp):
    1.  
    2.     private bool GameIsOnline = false;
    3.     private void SetInternetAccess(bool isOn)
    4.     {
    5.         if (GameIsOnline != isOn)
    6.         {
    7.             if (isOn)
    8.             {
    9.                 //Internet is Active.
    10.                 Debug.Log("Enabling Internet related content.");
    11.             }
    12.             else
    13.             {
    14.                 //Internet is NOT Active.
    15.                 Debug.Log("Disabling Internet related content.");
    16.             }
    17.             GameIsOnline = isOn;
    18.         }
    19.     }
    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.
     
    nikokoneko likes this.