Create a gist now

Instantly share code, notes, and snippets.

On Mac OS X: Block until the network stack is ready. Useful for daemons which need the network to do anything useful.
#import <Foundation/Foundation.h>
#import <SystemConfiguration/SystemConfiguration.h>
// Wait for the network to be configured. Equivalent to `ipconfig waitall`. Adapted from ipconfig/client.c
static void _doneWaitingForNetwork(SCDynamicStoreRef session, CFArrayRef changes, void * arg){
#define STARTUP_KEY CFSTR("Plugin:IPConfiguration")
#define NETWORK_RUN_LOOP_MODE CFSTR("WaitingForNetwork")
void waitForNetwork(){
SCDynamicStoreRef session = SCDynamicStoreCreate(NULL, (CFStringRef)[[NSProcessInfo processInfo] processName], _doneWaitingForNetwork, NULL);
if (session == NULL) {
asl_log(NULL, NULL, ASL_LEVEL_ERR, "SCDynamicStoreCreate failed while checking for network: %s", SCErrorString(SCError()));
CFMutableArrayRef keys = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
CFArrayAppendValue(keys, STARTUP_KEY);
SCDynamicStoreSetNotificationKeys(session, keys, NULL);
CFRunLoopSourceRef rls = SCDynamicStoreCreateRunLoopSource(NULL, session, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), rls, NETWORK_RUN_LOOP_MODE);
CFPropertyListRef value = SCDynamicStoreCopyValue(session, STARTUP_KEY);
if (value == NULL) {
CFRunLoopRunInMode(NETWORK_RUN_LOOP_MODE, 90, false);
} else {
CFRunLoopRemoveSource(CFRunLoopGetCurrent(), rls, NETWORK_RUN_LOOP_MODE);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment