I know this is a little outdated, but the selected answer is not perfect.
The SCReachability API can be used to know when a particular host is available. If all you want to know is when a valid IP address is assigned (rather than a viable route to the destination IP address), then you should look at the SCDynamicStore * API. These functions allow you to subscribe to the system configuration store for notification when certain values change. Thus, for notification, when the IPv4 address changes on any interface, you would do the following (error checking removed for readability)
SCDynamicStoreRef dynStore;
SCDynamicStoreContext context = {0, NULL, NULL, NULL, NULL};
dynStore = SCDynamicStoreCreate(kCFAllocatorDefault,
CFBundleGetIdentifier(CFBundleGetMainBundle()),
scCallback,
&context);
const CFStringRef keys[3] = {
CFSTR("State:/Network/Interface/.*/IPv4")
};
CFArrayRef watchedKeys = CFArrayCreate(kCFAllocatorDefault,
(const void **)keys,
1,
&kCFTypeArrayCallBacks);
if (!SCDynamicStoreSetNotificationKeys(dynStore,
NULL,
watchedKeys))
{
CFRelease(watchedKeys);
fprintf(stderr, "SCDynamicStoreSetNotificationKeys() failed: %s", SCErrorString(SCError()));
CFRelease(dynStore);
dynStore = NULL;
return -1;
}
CFRelease(watchedKeys);
rlSrc = SCDynamicStoreCreateRunLoopSource(kCFAllocatorDefault, dynStore, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), rlSrc, kCFRunLoopDefaultMode);
CFRelease(rlSrc);
You will need to display the scCallback function, which will be called whenever there is a change. Also you need to call CFRunLoopRun somewhere to make the code.
source
share