Search Unity

  1. Unity 2020.2 has been released.
    Dismiss Notice
  2. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

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.
     
    guetta18 and TheKingOfTheRoad like this.
  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:
    1
    Best answer , clean and easy.
     
  5. Piflik

    Piflik

    Joined:
    Sep 11, 2011
    Posts:
    250
    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. HonorableDaniel

    HonorableDaniel

    Joined:
    Feb 28, 2007
    Posts:
    2,970
    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:
    24
    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.
     
  8. elenzil

    elenzil

    Joined:
    Jan 23, 2014
    Posts:
    70
    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.
     
    TheKingOfTheRoad and WILEz1975 like this.
  9. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    9,866
    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:
    40
    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
    TheKingOfTheRoad likes this.
  11. Hoorza

    Hoorza

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

    tbigham

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

    TheKingOfTheRoad

    Joined:
    Apr 24, 2013
    Posts:
    242
    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.
     
  15. joshcamas

    joshcamas

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

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    9,866
    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.
     
  17. jfa257

    jfa257

    Joined:
    Jul 17, 2013
    Posts:
    6
    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:
    10
    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.
     
  19. garrido86

    garrido86

    Joined:
    Dec 17, 2013
    Posts:
    198
    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.
     
    joshcamas likes this.
  20. joshcamas

    joshcamas

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

    kenangamemcreator

    Joined:
    Mar 7, 2020
    Posts:
    2
    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?
     
    AcidFz and DhiaSendi like this.
  22. joshcamas

    joshcamas

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

    KEric

    Joined:
    Jan 11, 2013
    Posts:
    44
    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
    mahdad_baghani 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:
    12

    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:
    6
    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. TheKingOfTheRoad

    TheKingOfTheRoad

    Joined:
    Apr 24, 2013
    Posts:
    242
    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. OmegaNemesis28

    OmegaNemesis28

    Joined:
    Dec 1, 2012
    Posts:
    105
    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. Geo_skango

    Geo_skango

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

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    9,866
    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:
    77
    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:
    54
    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:
    105
    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:
    9,866
    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:
    105
    Joe-Censored likes this.
unityunity