Reachability.m 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. /*
  2. File: Reachability.m
  3. Abstract: Basic demonstration of how to use the SystemConfiguration Reachablity APIs.
  4. Version: 2.2
  5. Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc.
  6. ("Apple") in consideration of your agreement to the following terms, and your
  7. use, installation, modification or redistribution of this Apple software
  8. constitutes acceptance of these terms. If you do not agree with these terms,
  9. please do not use, install, modify or redistribute this Apple software.
  10. In consideration of your agreement to abide by the following terms, and subject
  11. to these terms, Apple grants you a personal, non-exclusive license, under
  12. Apple's copyrights in this original Apple software (the "Apple Software"), to
  13. use, reproduce, modify and redistribute the Apple Software, with or without
  14. modifications, in source and/or binary forms; provided that if you redistribute
  15. the Apple Software in its entirety and without modifications, you must retain
  16. this notice and the following text and disclaimers in all such redistributions
  17. of the Apple Software.
  18. Neither the name, trademarks, service marks or logos of Apple Inc. may be used
  19. to endorse or promote products derived from the Apple Software without specific
  20. prior written permission from Apple. Except as expressly stated in this notice,
  21. no other rights or licenses, express or implied, are granted by Apple herein,
  22. including but not limited to any patent rights that may be infringed by your
  23. derivative works or by other works in which the Apple Software may be
  24. incorporated.
  25. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
  26. WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
  27. WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  28. PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
  29. COMBINATION WITH YOUR PRODUCTS.
  30. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
  31. CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
  32. GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  33. ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR
  34. DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF
  35. CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF
  36. APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  37. Copyright (C) 2010 Apple Inc. All Rights Reserved.
  38. */
  39. #import <sys/socket.h>
  40. #import <netinet/in.h>
  41. #import <netinet6/in6.h>
  42. #import <arpa/inet.h>
  43. #import <ifaddrs.h>
  44. #import <netdb.h>
  45. #import <CoreFoundation/CoreFoundation.h>
  46. #import "Reachability.h"
  47. #define kShouldPrintReachabilityFlags 1
  48. static void PrintReachabilityFlags(SCNetworkReachabilityFlags flags, const char* comment)
  49. {
  50. #if kShouldPrintReachabilityFlags
  51. APLog(@"Reachability Flag Status: %c%c %c%c%c%c%c%c%c %s\n",
  52. (flags & kSCNetworkReachabilityFlagsIsWWAN) ? 'W' : '-',
  53. (flags & kSCNetworkReachabilityFlagsReachable) ? 'R' : '-',
  54. (flags & kSCNetworkReachabilityFlagsTransientConnection) ? 't' : '-',
  55. (flags & kSCNetworkReachabilityFlagsConnectionRequired) ? 'c' : '-',
  56. (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) ? 'C' : '-',
  57. (flags & kSCNetworkReachabilityFlagsInterventionRequired) ? 'i' : '-',
  58. (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) ? 'D' : '-',
  59. (flags & kSCNetworkReachabilityFlagsIsLocalAddress) ? 'l' : '-',
  60. (flags & kSCNetworkReachabilityFlagsIsDirect) ? 'd' : '-',
  61. comment
  62. );
  63. #endif
  64. }
  65. @implementation Reachability
  66. static void ReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void* info)
  67. {
  68. #pragma unused (target, flags)
  69. //We're on the main RunLoop, so an NSAutoreleasePool is not necessary, but is added defensively
  70. // in case someon uses the Reachablity object in a different thread.
  71. @autoreleasepool {
  72. Reachability* noteObject = (__bridge Reachability*) info;
  73. // Post a notification to notify the client that the network reachability changed.
  74. [[NSNotificationCenter defaultCenter] postNotificationName: kReachabilityChangedNotification object: noteObject];
  75. }
  76. }
  77. - (BOOL) startNotifier
  78. {
  79. BOOL retVal = NO;
  80. SCNetworkReachabilityContext context = {0, (__bridge void *)(self), NULL, NULL, NULL};
  81. if(SCNetworkReachabilitySetCallback(reachabilityRef, ReachabilityCallback, &context))
  82. {
  83. if(SCNetworkReachabilityScheduleWithRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode))
  84. {
  85. retVal = YES;
  86. }
  87. }
  88. return retVal;
  89. }
  90. - (void) stopNotifier
  91. {
  92. if(reachabilityRef!= NULL)
  93. {
  94. SCNetworkReachabilityUnscheduleFromRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
  95. }
  96. }
  97. - (void) dealloc
  98. {
  99. [self stopNotifier];
  100. if(reachabilityRef!= NULL)
  101. CFRelease(reachabilityRef);
  102. }
  103. + (Reachability*) reachabilityWithHostName: (NSString*) hostName;
  104. {
  105. Reachability* retVal = NULL;
  106. SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, [hostName UTF8String]);
  107. if(reachability!= NULL)
  108. {
  109. retVal= [[self alloc] init];
  110. if(retVal!= NULL)
  111. {
  112. retVal->reachabilityRef = reachability;
  113. retVal->localWiFiRef = NO;
  114. }
  115. }
  116. return retVal;
  117. }
  118. + (Reachability*) reachabilityWithAddress: (const struct sockaddr_in*) hostAddress;
  119. {
  120. SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)hostAddress);
  121. Reachability* retVal = NULL;
  122. if(reachability!= NULL)
  123. {
  124. retVal= [[self alloc] init];
  125. if(retVal!= NULL)
  126. {
  127. retVal->reachabilityRef = reachability;
  128. retVal->localWiFiRef = NO;
  129. }
  130. }
  131. return retVal;
  132. }
  133. + (Reachability*) reachabilityForInternetConnection;
  134. {
  135. struct sockaddr_in zeroAddress;
  136. bzero(&zeroAddress, sizeof(zeroAddress));
  137. zeroAddress.sin_len = sizeof(zeroAddress);
  138. zeroAddress.sin_family = AF_INET;
  139. return [self reachabilityWithAddress: &zeroAddress];
  140. }
  141. + (Reachability*) reachabilityForLocalWiFi;
  142. {
  143. struct sockaddr_in localWifiAddress;
  144. bzero(&localWifiAddress, sizeof(localWifiAddress));
  145. localWifiAddress.sin_len = sizeof(localWifiAddress);
  146. localWifiAddress.sin_family = AF_INET;
  147. // IN_LINKLOCALNETNUM is defined in <netinet/in.h> as 169.254.0.0
  148. localWifiAddress.sin_addr.s_addr = htonl(IN_LINKLOCALNETNUM);
  149. Reachability* retVal = [self reachabilityWithAddress: &localWifiAddress];
  150. if(retVal!= NULL)
  151. {
  152. retVal->localWiFiRef = YES;
  153. }
  154. return retVal;
  155. }
  156. #pragma mark Network Flag Handling
  157. - (NetworkStatus) localWiFiStatusForFlags: (SCNetworkReachabilityFlags) flags
  158. {
  159. PrintReachabilityFlags(flags, "localWiFiStatusForFlags");
  160. BOOL retVal = NotReachable;
  161. if((flags & kSCNetworkReachabilityFlagsReachable) && (flags & kSCNetworkReachabilityFlagsIsDirect))
  162. {
  163. retVal = ReachableViaWiFi;
  164. }
  165. return retVal;
  166. }
  167. - (NetworkStatus) networkStatusForFlags: (SCNetworkReachabilityFlags) flags
  168. {
  169. PrintReachabilityFlags(flags, "networkStatusForFlags");
  170. if ((flags & kSCNetworkReachabilityFlagsReachable) == 0)
  171. {
  172. // if target host is not reachable
  173. return NotReachable;
  174. }
  175. BOOL retVal = NotReachable;
  176. if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0)
  177. {
  178. // if target host is reachable and no connection is required
  179. // then we'll assume (for now) that your on Wi-Fi
  180. retVal = ReachableViaWiFi;
  181. }
  182. if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) ||
  183. (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))
  184. {
  185. // ... and the connection is on-demand (or on-traffic) if the
  186. // calling application is using the CFSocketStream or higher APIs
  187. if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)
  188. {
  189. // ... and no [user] intervention is needed
  190. retVal = ReachableViaWiFi;
  191. }
  192. }
  193. if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
  194. {
  195. // ... but WWAN connections are OK if the calling application
  196. // is using the CFNetwork (CFSocketStream?) APIs.
  197. retVal = ReachableViaWWAN;
  198. }
  199. return retVal;
  200. }
  201. - (BOOL) connectionRequired;
  202. {
  203. NSAssert(reachabilityRef != NULL, @"connectionRequired called with NULL reachabilityRef");
  204. SCNetworkReachabilityFlags flags;
  205. if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags))
  206. {
  207. return (flags & kSCNetworkReachabilityFlagsConnectionRequired);
  208. }
  209. return NO;
  210. }
  211. - (NetworkStatus) currentReachabilityStatus
  212. {
  213. NSAssert(reachabilityRef != NULL, @"currentNetworkStatus called with NULL reachabilityRef");
  214. NetworkStatus retVal = NotReachable;
  215. SCNetworkReachabilityFlags flags;
  216. if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags))
  217. {
  218. if(localWiFiRef)
  219. {
  220. retVal = [self localWiFiStatusForFlags: flags];
  221. }
  222. else
  223. {
  224. retVal = [self networkStatusForFlags: flags];
  225. }
  226. }
  227. return retVal;
  228. }
  229. @end