Created
February 24, 2011 17:16
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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