NSNotification network connection for OSX?

I just need to have a notification when a valid IP address is assigned. I tried the survey through SCReachability, but it seems inefficient.

Any suggestions? It seems like it should be simple, but I struggled for hours to get something to work.

+3
source share
2 answers

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.

+10
source

SCNetworkReachability. , . .

. Apple Reachability, , Objective-C. iPhone, , Reachability.{m,h} OS X.

(. Apple SimpleReach. , .)

+1

Source: https://habr.com/ru/post/1747123/


All Articles