Reputation: 54600
I want to provide my user with some meaningful error messages when network requests fail.
On Windows I can call InternetGetConnectedState() to see if there is an active network connection. What is the OS X equivalent?
Bonus points for example code if it's complex.
Upvotes: 4
Views: 1540
Reputation:
Don't look for an active network connection, look for your target host being reachable. It's not complex, so no example code :-)
Update: I think I should have explained what reachable means in this context. As described in the docs, a remote network address is considered reachable if a packet destined for that address could leave this computer via any network interface. This is, roughly speaking, an expression of the fact that the i/f is configured and able to either directly deliver to the remote system, or has a route available to get to it. Reachability doesn't describe anything relating to whether the remote host is 'up' or whether the network between this computer and the remote one is functioning properly.
Upvotes: 3
Reputation: 47163
If you run the ifconfig command-line tool, you get output like this:
en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
ether 00:0d:93:48:d8:f2
media: autoselect (none) status: inactive
supported media: none autoselect 10baseT/UTP <half-duplex> 10baseT/UTP <full-duplex> 10baseT/UTP <full-duplex,hw-loopback> 100baseTX <half-duplex> 100baseTX <full-duplex> 100baseTX <full-duplex,hw-loopback> 1000baseT <full-duplex> 1000baseT <full-duplex,hw-loopback> 1000baseT <full-duplex,flow-control> 1000baseT <full-duplex,flow-control,hw-loopback>
en1: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
inet6 fe80::211:24ff:fe27:385f%en1 prefixlen 64 scopeid 0x5
inet 192.168.1.67 netmask 0xffffff00 broadcast 192.168.1.255
ether 00:11:24:27:38:5f
media: autoselect status: active
supported media: autoselect
In my case, note that my en0 is not connected, and my en1 is. Correspondingly, there is either 'status:active' or 'status: inactive'. You could run ifconfig, parse the output, and see if there are any active interfaces. Apart from loopback.
There are probably more API-ish ways to do this, but i can't tell you what they are!
Upvotes: 1
Reputation: 85035
The SystemConfiguration framework is also exposed through a simple command line utility, scutil(8)
:
$ scutil -r stackoverflow.com
Reachable
Upvotes: 1
Reputation: 10665
OSX actively supports changes in the network/connection situation, and reconfigures any time there is a change. As a consequence it expects application developers to not assume the network will always stay the same. You might find System Configuration Goals and Architecture an interesting read, as well as checking up on the workings of configd. (This is just from reading about it, I've never actually programmed anything like this on the mac)
Upvotes: 1