How can I detect if any network adapter is connected? I can only find examples on using NSReachability to detect an internet connection, but I want to detect even a non-internet network connection. Getting the IP-adress on eth0 should work? I'm working on Mac only.
Getting a List of All IP Addresses in Apple's Technical Note TN1145 mentions 3 methods for getting the status of the network interfaces:
System Configuration Framework: This is Apple's recommended way and there is sample code in the TN1145. The advantage is that it provides a way to get notified of changes in the interface configuration.
Open Transport API: There is also sample code in TN1145, otherwise I cannot say much about it. (There is only "legacy" documentation on the Apple website.)
BSD sockets: This seems to be the easiest way to get the list of interfaces and to determine the connection status (if you don't need dynamic change notifications).
The following code demonstrates how to find all IPv4 and IPv6 interfaces that are "up and running".
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <ifaddrs.h>
#include <net/if.h>
#include <netdb.h>
struct ifaddrs *allInterfaces;
// Get list of all interfaces on the local machine:
if (getifaddrs(&allInterfaces) == 0) {
struct ifaddrs *interface;
// For each interface ...
for (interface = allInterfaces; interface != NULL; interface = interface->ifa_next) {
unsigned int flags = interface->ifa_flags;
struct sockaddr *addr = interface->ifa_addr;
// Check for running IPv4, IPv6 interfaces. Skip the loopback interface.
if ((flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING)) {
if (addr->sa_family == AF_INET || addr->sa_family == AF_INET6) {
// Convert interface address to a human readable string:
char host[NI_MAXHOST];
getnameinfo(addr, addr->sa_len, host, sizeof(host), NULL, 0, NI_NUMERICHOST);
printf("interface:%s, address:%s\n", interface->ifa_name, host);
}
}
}
freeifaddrs(allInterfaces);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With