Ping make my android app crash if no internet connection

Hi,

I am looking for a system which determine if internet is available when i launch my app.
After searching on internet i have try many solution and on editor this one works :

	IEnumerator CheckConnectionToMasterServer() {
		Ping pingMasterServer = new Ping("74.125.224.72");
		float startTime = Time.time;
		while (!pingMasterServer.isDone && Time.time < startTime + 5.0f) {
			
			yield return new WaitForSeconds(5.0f);
		}
		if(pingMasterServer.isDone && pingMasterServer.time > 2) {
			
			Debug.Log ("IntenetON" );
			
			
		} if(pingMasterServer.isDone && pingMasterServer.time<=1) {
			
			Debug.Log ("IntenetOFF" );
		}
	}

When i build an apk for android there is no problem, ping works (cause i am connected to wifi).

If i launch with no internet connection my app instantly crash
I have try to comment the while and always wait 5 seconds to check the ping result and its still crashing…

Anyone can solve this issue ?
Thank you.

Easy, you don’t have a try/catch block around your method.

I didn’t find the overload constructor for Ping(string), but I assume it’s the same as creating a Ping class then doing Send(string) (i.e. it immediately attempts to ping the address provided in the string).

If you check the documentation for Ping.Send(string) it throws various exceptions you have to deal with (otherwise your program will crash).

Best guess is it’s throwing the PingException since it can’t resolve the address. Catch the exception, then do something that makes sense for your application (warn user can’t ping or what have you).

     IEnumerator CheckConnectionToMasterServer() {
       try{
         Ping pingMasterServer = new Ping("74.125.224.72");
         float startTime = Time.time;
         while (!pingMasterServer.isDone && Time.time < startTime + 5.0f) {
             
             yield return new WaitForSeconds(5.0f);
         }
         if(pingMasterServer.isDone && pingMasterServer.time > 2) {
             
             Debug.Log ("IntenetON" );
             
             
         } if(pingMasterServer.isDone && pingMasterServer.time<=1) {
             
             Debug.Log ("IntenetOFF" );
         }
       }
       catch (exception e)
       {
         Debug.LogWarning("Couldn't ping: " + e.message);

       }
     }