Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for internet connectivity from Unity

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?

like image 606
Anna Kuleva Avatar asked Dec 07 '15 16:12

Anna Kuleva


People also ask

How do I check my Unity internet status?

Android: ICMP sockets are used for ping operation if they're available, otherwise Unity spawns a child process /system/bin/ping for ping operations. To check if ICMP sockets are available, you need to read the contents for /proc/sys/net/ipv4/ping_group_range.


Video Answer


1 Answers

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.

like image 134
Maximillian Laumeister Avatar answered Sep 18 '22 16:09

Maximillian Laumeister