Skip to content

Instantly share code, notes, and snippets.

@s4y
Created February 24, 2011 17:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save s4y/842476 to your computer and use it in GitHub Desktop.
Save s4y/842476 to your computer and use it in GitHub Desktop.
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){
CFRunLoopStop(CFRunLoopGetCurrent());
}
#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()));
exit(EXIT_FAILURE);
}
CFMutableArrayRef keys = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
CFArrayAppendValue(keys, STARTUP_KEY);
SCDynamicStoreSetNotificationKeys(session, keys, NULL);
CFRelease(keys);
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 {
CFRelease(value);
}
CFRunLoopRemoveSource(CFRunLoopGetCurrent(), rls, NETWORK_RUN_LOOP_MODE);
CFRelease(rls);
CFRelease(session);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment