script to check if I the network is up or not

My server sends many emails via Applescript. But I get errors in Mail that the network is not available. I suspect the machine is sleeping and Mail tries to send the mail before a network connection is established, (hardwired).

I found the following script.

repeat until (do shell script "/sbin/ping -c1 www.google.com") contains "0% packet loss"
	delay 5 --  This will run the ping at 5 second intervals until there's no packet loss. 
end repeat

However, that does not seem to work properly. I explain. If I run it with a non-existing address, it does not keep running but sends the following error.

tell current application
	do shell script "/sbin/ping -c1 www.gle.com"
		--> error "PING www.gle.com (34.206.12.234): 56 data bytes

--- www.gle.com ping statistics ---
1 packets transmitted, 0 packets received, 100.0% packet loss" number 2
Result:
error "PING www.gle.com (34.206.12.234): 56 data bytes

--- www.gle.com ping statistics ---
1 packets transmitted, 0 packets received, 100.0% packet loss" number 2

The error box states:

PING www.gle.com (34.206.12.234): 56 data bytes

www.gle.com ping statistics —
1 packets transmitted, 0 packets received, 100.0% packet loss

I discovered this as I get sometimes errors in the script running that point to this.

If I run it with the network disconnected, I get:

tell current application
	do shell script "/sbin/ping -c1 www.goole.com"
		--> error "ping: cannot resolve www.goole.com: Unknown host" number 68
Result:
error "ping: cannot resolve www.goole.com: Unknown host" number 68

I hope this is enough information for you to answer my query.

What I like to achieve is that it checks if I have a network connection and keeps doing so till it has that connection and then executes the rest of the script.

Any idea how to fix this?

PS OS10.15

Here is a pic of the error.

https://ibb.co/mBFG0jP

Other approach, using try block:


repeat
	try
		set pingRequest to do shell script "/sbin/ping -c1 www.goovcgle.com"
		if pingRequest contains "0% packet loss" then exit repeat
		-- This will run the ping at 5 second intervals until there's no packet loss. 
	on error
		display dialog "The connection is bad or is absent at all" giving up after 5
	end try
end repeat

This will keep executing of the script. It is infinitive loop, so you should connect to the Internet when it is OFF.

thanks and it works.

there is a small error in the google line, here is the corrected version.

repeat
	try
		set pingRequest to do shell script "/sbin/ping -c1 www.google.com"
		if pingRequest contains "0% packet loss" then exit repeat
		-- This will run the ping at 5 second intervals until there's no packet loss. 
	on error
		display dialog "The connection is bad or is absent at all" giving up after 5
	end try
end repeat