Created
May 24, 2011 18:15
-
-
Save mattstevens/989296 to your computer and use it in GitHub Desktop.
Monitoring for IP address changes
This file contains hidden or 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 "NetworkMonitor.h" | |
NSString *NetworkConfigurationDidChangeNotification = @"NetworkConfigurationDidChangeNotification"; | |
void storeCallback(SCDynamicStoreRef store, CFArrayRef changedKeys, void *info) { | |
[(NetworkMonitor *)info update]; | |
} | |
@implementation NetworkMonitor | |
@synthesize addresses; | |
@synthesize computerName; | |
- (id)init { | |
if (self = [super init]) { | |
ipv4Pattern = (NSString *)SCDynamicStoreKeyCreateNetworkServiceEntity(NULL, | |
kSCDynamicStoreDomainState, | |
kSCCompAnyRegex, | |
kSCEntNetIPv4); | |
ipv6Pattern = (NSString *)SCDynamicStoreKeyCreateNetworkServiceEntity(NULL, | |
kSCDynamicStoreDomainState, | |
kSCCompAnyRegex, | |
kSCEntNetIPv6); | |
computerNamePattern = (NSString *)SCDynamicStoreKeyCreateComputerName(NULL); | |
return self; | |
} else { | |
return nil; | |
} | |
} | |
- (void)dealloc { | |
[ipv4Pattern release]; | |
[ipv6Pattern release]; | |
[computerNamePattern release]; | |
self.addresses = nil; | |
self.computerName = nil; | |
CFRelease(store); | |
[super dealloc]; | |
} | |
- (void)startMonitoring { | |
SCDynamicStoreContext context; | |
memset(&context, 0, sizeof(context)); | |
context.info = self; | |
store = SCDynamicStoreCreate(NULL, CFSTR("NetworkMonitor"), storeCallback, &context); | |
if (store == NULL) { | |
// The horror! | |
return; | |
} | |
[self update]; | |
NSArray *patterns = [NSArray arrayWithObjects:ipv4Pattern, ipv6Pattern, computerNamePattern, nil]; | |
if (!SCDynamicStoreSetNotificationKeys(store, NULL, (CFArrayRef)patterns)) { | |
// More horror! | |
} | |
SCDynamicStoreSetDispatchQueue(store, dispatch_get_main_queue()); | |
} | |
- (void)update { | |
NSMutableArray *newAddresses = [NSMutableArray array]; | |
NSArray *patterns = [NSArray arrayWithObject:ipv4Pattern]; | |
NSDictionary *info = [(NSDictionary *)SCDynamicStoreCopyMultiple(store, NULL, (CFArrayRef)patterns) autorelease]; | |
[info enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { | |
NSArray *serviceAddresses = [obj objectForKey:(NSString *)kSCPropNetIPv4Addresses]; | |
[newAddresses addObjectsFromArray:serviceAddresses]; | |
}]; | |
self.addresses = newAddresses; | |
self.computerName = [(NSString *)SCDynamicStoreCopyComputerName(NULL, NULL) autorelease]; | |
[[NSNotificationCenter defaultCenter] postNotificationName:NetworkConfigurationDidChangeNotification object:self]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey, I know this is super late but can you share the header file for this? Thanks!