Testing for network connectivity in a script
Sun Dec 19 13:50:41 2004 Testing for Search Keys: network
Sometimes a script needs to know if it has network or internet connectivity before it continues, or perhaps its whole purpose is the report a loss of connectivity or inability to reach specific services.
A typical response to such a problem is to use "ping" to determine if some other host is "up". That's pretty simplistic, though, and really doesn't tell the whole story.
If you really want to test connectivity, and want the script to be able to tell you where the problems are when it is lacking, you need a more procedural approach. First, ping something on your local network, using a "-c5" or even a larger count (don't use the "-w" flag here). The reason for a larger count rather than the commonly advised "-c1" is that very temporary and unimportant problems can cause single packet loss. This *shouldn't* be on your local network, but asking for more packets gives you more information about the situation if you do have this problem. Similarly, the reason not to use -w1 or -w anything (which times out after that many seconds) is because temporarily slow does not mean not connected.
Use a numeric ip address for this first test so that you aren't triggering dns name resolution. Test more than one address in case one host is down. If none of these work, you know you have serious local problems: either your nic isn't working or connected, or the rest of your network is down.
Next try the router on your lan segment, again using numeric ip addresses. If that doesn't respond, you won't be going off-network, so you can stop now.
If these tests succeed, you still don't really know that you have connectivity, so I'd next try the closest thing I know - like my isp's dns or mail server. Depending on how seriously you define "connectivity", I'd then move on to checking things farther away or the things I already know I need to talk to.
If you have had any indications of failure, increase -c to get an idea of how bad the loss actually is. Somewhere in here I'd check with a hostname or two, to see that DNS is working.
Consider that ping doesn't absolutely say you have any high level connectivity, so if you REALLY need to know, then you need to do more, like a lynx dump for a web page, a test ftp connection, or whatever tells you that by gum you really do have full connectivity. If your purpose is to specific hosts, that's all you need to know, but if your concern is general connectivity, then you need to test a range of hosts.
Your script may also want to check "ifconfig" and "netstat -i" if it is logging problems. Changes of netstat -i stats in the error columns over a short period of time probably indicates serious problems.
Got something to add? Send me email.
(OLDER) <- More Stuff -> (NEWER) (NEWEST)
Printer Friendly Version
Increase ad revenue 50-250% with Ezoic