Connectivity check, quickly, in a script
I'm writing a perl script, and in it I want to see if I'm connected to the internet (I'm using a cable modem).
I tried ping (setting the -w option set to 1, or the -W option set to 1, or the -t option set to 1) but if I'm not connected, it hangs (I don't know how long it hangs, but it's over a half minute before I kill it. If I'm not connected, I don't want it hanging for more than a second) Ideally, I'd like a command which would come back within a second saying I'm not connected. Also tried ftp, wget, whois... they all hang for a long time if not connected. Thanks in advance. |
Use ping as follows:
ping -c 1 YOUR-HOST.COM |
Quote:
|
Are using a numeric ip address? If you are not, ping will hang much longer (though it will still return) because it first has to resolve the host name.
But even with a numeric address, it isn't going to return instantly, and you wouldn't want it to, because networks can be slow. I'd "ping -c1" my (numeric) gateway address first. If that fails, you are definitely going nowhere. If that's on your lan, then "-w 1" is fine, but I would not use -w for anything past a local router because temporarily slow does not mean not connected. If it succeeds, 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. Further, 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. -- Tony Lawrence http://aplawrence.com |
Thanks, pcunix and nixcraft, for your replys.
I won't go into why I needed to see if I was connected, quickly, but here's how I solved it, in case anyone's interested. In my script, I grabbed the RX bytes from ifconfig for my eth0 interface. I then forked a 'ping -c 1' process. After a second, I checked the RX bytes to see if they had changed. Ahh perl. The duct tape of the Internet. Thanks again :) |
You can also check the return status of the ping command. It will return 0 if it was able to ping the remote host, and 1 otherwise. This is probably more reliable, because just the face that your ethernet interface received a packet doesn't necessarily mean that you're connected (the received packet xcould've been from your gateway, for instance).
|
Quote:
You are right, though. My solution wouldn't work if I was going through a gateway. But I'm not, so it works for me :D |
All times are GMT -5. The time now is 10:13 PM. |