16

I have a Unity project which I build for Android and iOS platforms. I want to check for internet connectivity on Desktop, Android, and iOS devices. I've read about three different solutions:

  1. Ping something (for example Google) - I totally dislike such decision, and I've read about mistakes on Android.

  2. Application.internetReachability - According to Unity's documentation, this function will only determine that I have a POSSIBILITY of connecting to the Internet (it doesn't guarantee a real connection).

  3. Network.TestConnection() - If I have no Internet connection, my application fails. So this isn't correct either.

How can I determine whether I have internet connectivity from within Unity?

Mikepote
  • 5,225
  • 1
  • 30
  • 35
Anna Kuleva
  • 169
  • 1
  • 1
  • 3
  • 5
    Why would `Network.TestConnection()` cause your application to fail? Seems like a little error handling would easily catch that. – Ron Beyer Dec 07 '15 at 16:43
  • 1
    Please link to the mentioned "mistakes" with the pinging approach? – SimpleVar Dec 07 '15 at 16:47
  • @RonBeyer , if I use Network.TestConnection(), and have no Internet Connection, my Application fails with following exception: 'Cannot resolve connection tester address, you must be connected to the internet before performing this or set the address to something accessible to you.' I copied cope from http://docs.unity3d.com/ScriptReference/Network.TestConnection.html – Anna Kuleva Dec 07 '15 at 16:59
  • 2
    @AnnaKuleva If `Network.TestConnection()` only throws the exception when there is no internet, just wrap it in a `try-catch`. Error means no internet, and no error means you can look at the test results. – SimpleVar Dec 07 '15 at 17:03
  • @RonBeyer There are a lot of topics were people try to catch this exception) I haven't seen any ready answer yet. If you give me a link with the answer, I would said "Thank you". – Anna Kuleva Dec 07 '15 at 17:05
  • @SamB , I need one solution for two different platforms (if it's possible). How to do it for ios-platform, I've already known. – Anna Kuleva Dec 07 '15 at 17:08
  • 3
    This is definitely not a duplicate of the linked question. This question is asking about how to check for connectivity using C# from within Unity3D on PC, Android and iOS. The proposed duplicate is asking how to check for connectivity using Objective-C from the iOS SDK, using Cocoa Touch. These are two completely separate programming languages and technology stacks. – Maximillian Laumeister Dec 08 '15 at 19:02

6 Answers6

10

I don't actually believe that Network.TestConnection() is the right tool for this job. According to the documentation, it looks to me like it's meant for testing if NAT is working and your client is publicly reachable by IP, but what you want to check for is whether you have general internet connectivity.

Here is a solution that I found on Unity Answers by user pixel_fiend, which simply tests a website to see if the user has connectivity. One benefit of this code is that it uses IEnumerator for asynchronous operation, so the connectivity test won't hold up the rest of your application:

IEnumerator checkInternetConnection(Action<bool> action){
     WWW www = new WWW("http://google.com");
     yield return www;
     if (www.error != null) {
         action (false);
     } else {
         action (true);
     }
 } 
 void Start(){
     StartCoroutine(checkInternetConnection((isConnected)=>{
         // handle connection status here
     }));
 }

You can change the website to whatever you want, or even modify the code to return success if any one of a number of sites are reachable. AFAIK there is no way to check for true internet connectivity without trying to connect to a specific site on the internet, so "pinging" one or more websites like this is likely to be your best bet at determining connectivity.

Maximillian Laumeister
  • 18,162
  • 7
  • 50
  • 70
6
    public static IEnumerator CheckInternetConnection(Action<bool> syncResult)
    {
        const string echoServer = "http://google.com";

        bool result;
        using (var request = UnityWebRequest.Head(echoServer))
        {
            request.timeout = 5;
            yield return request.SendWebRequest();
            result = !request.isNetworkError && !request.isHttpError && request.responseCode == 200;
        }
        syncResult(result);
    }
Kirill Belonogov
  • 348
  • 3
  • 11
2

i know this is old, but maybe can help you.

public bool CheckInternetConnection(){
    return !(Application.internetReachability == NetworkReachability.NotReachable)
}
kamiyar
  • 179
  • 1
  • 9
  • Is it working on mobile devices with Android and iOS? – Skylin R Oct 16 '19 at 06:15
  • 1
    yes, i tested, this is work on all devices and platforms – kamiyar Oct 17 '19 at 13:48
  • 1
    Did you read the question? It says right there that this is insufficient. The documentation says this only suggests there is a network available, not that the network has connectivity. For example, wifi connection to a router but the router has no external connection. There's even a duplicate downvote answer. – user99999991 Jul 28 '20 at 01:50
  • 1
    Application.internetReachability is not for actual connection – Saad Anees Nov 09 '20 at 10:52
1
void Start()
{
    StartCoroutine(CheckInternetConnection(isConnected =>
    {
        if (isConnected)
        {
            Debug.Log("Internet Available!");
        }
        else
        {
            Debug.Log("Internet Not Available");
        }
    }));
}

IEnumerator CheckInternetConnection(Action<bool> action)
{
    UnityWebRequest request = new UnityWebRequest("http://google.com");
    yield return request.SendWebRequest();
    if (request.error != null) {
        Debug.Log ("Error");
        action (false);
    } else{
        Debug.Log ("Success");
        action (true);
    }
}

Since WWW has deprecated, UnityWebRequest can be used instead.

Arkar Min Tun
  • 301
  • 3
  • 6
0

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

As for the iOS version unfortunately I don't have enough of knowledge in this area. It would be nice if someone could extend the repo to include the iOS version too.

Eric
  • 1,308
  • 12
  • 29
-1

You can check network connection using this code

if(Application.internetReachability == NetworkReachability.NotReachable){
       Debug.Log("Error. Check internet connection!");
}
Codemaker
  • 4,115
  • 1
  • 32
  • 30
  • see for check conn, and its type -> https://docs.unity3d.com/ScriptReference/NetworkReachability.ReachableViaLocalAreaNetwork.html However in regards to internetReachability: "Do not use this property to determine the actual connectivity. E.g. the device can be connected to a hot spot, but not have the actual route to the network." https://docs.unity3d.com/ScriptReference/Application-internetReachability.html – Sergio Solorzano May 27 '20 at 07:56