Re: How to determine if there is an internet connection available?
Re: How to determine if there is an internet connection available?
- Subject: Re: How to determine if there is an internet connection available?
- From: Jens Alfke <email@hidden>
- Date: Sat, 12 Nov 2011 10:19:04 -0800
On Nov 11, 2011, at 6:39 PM, Vojtěch Meluzín wrote:
> I'm using BSD sockets for some internet access, it works fine. But if there
> is no connection available, it waits for say 30 seconds completely stopping
> the application. Is there a way to determine if there is actually an
> internet connection, so that I can check before using sockets?
If there really is no active network interface, then making a socket connection will immediately fail with an error something like “no route to host”. The situation you’re seeing is more likely one where the link is up, but has trouble connecting upstream — for example, your WiFi router is working but the cable modem is down, or you have one bar of cell signal but can’t get enough packets through to establish a connection. In that case the situation is out of your device’s control; it has no idea what is going to happen to packets that it sends to the network, so it can’t tell you whether a network connection will work or not.
(An interesting intermediate situation is one where you do have an Internet connection, but not to the address you want to connect to. For example, you want to talk to an intranet server behind a firewall but the VPN tunnel isn’t up. This is why questions like “is there actually an Internet connection?” aren’t meaningful.)
So the general rules are:
1. Use the SystemConfiguration API to find out whether the host you’re interested in is potentially reachable, i.e. any network interface is up. You can either ask directly or set up notifications.
2. If you’re calling an API that wants a raw IP address, resolve the hostname asynchronously or on a background thread, since otherwise the DNS lookup could lock up your thread for some time waiting for an upstream resolver to reply.
3. Try to make a connection. Do this asynchronously or on a background thread. Never do synchronous network I/O on the main thread.
4. If the connection fails, assume you’re currently offline, and retry only after the network configuration changes or the user requests a reconnect.
—Jens
Attachment:
smime.p7s
Description: S/MIME cryptographic signature
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden