On Jul 9, 2008, at 8:22 AM, xiaobin wrote:

Hello,

I am writing a program to detect the status of network.

In my program, I need get the status of network when the connection is
set disable.  here it is not by connecting the network to get the
status.
which API or method can work for it?

I've used two methods in previous projects. This is all CoreFoundation code that I used in daemons but should work just fine in a Cocoa environment.

1) If you just want to know whether the system is connected to a network then you can lookup the default router. If the default router is present then you could assume that the network is up.

CFStringRef CFXGetDefaultIPv4RouterCopy()
{
   CFStringRef result = NULL;

SCDynamicStoreRef dynamicStore = SCDynamicStoreCreate(NULL, CFSTR("StefansCoreFoundationExtensions"), NULL, NULL);
   if (dynamicStore != NULL) {
CFDictionaryRef properties = (CFDictionaryRef) SCDynamicStoreCopyValue(dynamicStore, CFSTR("State:/Network/Global/ IPv4"));
      if (properties != NULL) {
result = (CFStringRef) CFDictionaryGetValue(properties, CFSTR("Router"));
         if (result != NULL) {
            CFRetain(result);
         }
         CFRelease(properties);
      }
      CFRelease(dynamicStore);
   }

   return result;
}

2) If you want to continuously monitor the network status then you can ask the System Configuration framework to let you know then the default route changed.

void DefaultRouteHasChanged(SCDynamicStoreRef store, CFArrayRef changedKeys, void *info)
{
   ...
}

void Foo()
{
   ...

   // Start a watcher to keep track of State:/Network/Global/IPv4

   SCDynamicStoreContext context = {0, NULL, NULL, NULL, NULL};
gDynamicStore = SCDynamicStoreCreate(NULL, CFSTR("SampleApp"), DefaultRouteHasChanged, &context);

CFStringRef key = SCDynamicStoreKeyCreate(NULL, CFSTR("%@/%@/%@/ %@"), kSCDynamicStoreDomainState, kSCCompNetwork,
      kSCCompGlobal, kSCEntNetIPv4);

CFArrayRef keyArray = CFArrayCreate(NULL, (const void **)(&key), 1, &kCFTypeArrayCallBacks);
   SCDynamicStoreSetNotificationKeys(gDynamicStore, keyArray, NULL);
   CFRelease(keyArray);
   CFRelease(key);

CFRunLoopSourceRef runLoopSource = SCDynamicStoreCreateRunLoopSource(NULL, gDynamicStore, 0); CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopCommonModes);
   CFRelease(runLoopSource);

   ...

   // Run the RunLoop

   CFRunLoopRun();
}

 S.

_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to [EMAIL PROTECTED]

Reply via email to