Check for active internet connection

Is there a method or utility ‘built-in’ to Unity to check for an active internet connection?
Coming from an Adobe AIR background there is something called URLMonitor which does this automatically.

//Checking for network connectivity
protected function onNetworkChange(e:Event):void
 {
    //  Alert.show("Your Network State changed", "INFO");
            monitor = new URLMonitor(new URLRequest('http://www.adobe.com'));
            monitor.addEventListener(StatusEvent.STATUS, netConnectivity);
            monitor.start();
        }

    protected function netConnectivity(e:StatusEvent):void
     {
         if(monitor.available)
           {
                Alert.show("Status change. You are connected to the internet", "INFO");
          }
           else
          {
                Alert.show("Status change. You are not connected to the internet", "INFO");
     }

      monitor.stop();
}

So it seems like it just pings that web address and lets you know if it was connected? Something like this should do the trick. “isOnline” in the following code will be updated with the current status every 5 seconds (plus the time it takes for the request to complete).

private UnityWebRequest adobeRequest;
public float pingInterval = 5f; //seconds
public static bool isOnline = false;
void Start() {
StartCoroutine(Ping() );
}

IEnumerator Ping() {
while (true) {
adobeRequest = new UnityWebRequest("http://www.adobe.com");
yield return adobeRequest;
isOnline =  !adobeRequest.isError;
yield return new WaitForSeconds(pingInterval);
}
}
1 Like

Yeah, there is no built-in method exactly for this, but trying to fetch a web page is pretty much the only reliable way to check for a working internet connection.

However, I would recommend picking a URL that leads to a lightweight page — something small, with no php, images, or includes, to be kind to the server as well as your user’s bandwidth. If you have your own web site, just throw a tiny text file up somewhere, and fetch that.