Reachability.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. /*
  2. Copyright (c) 2011, Tony Million.
  3. All rights reserved.
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions are met:
  6. 1. Redistributions of source code must retain the above copyright notice, this
  7. list of conditions and the following disclaimer.
  8. 2. Redistributions in binary form must reproduce the above copyright notice,
  9. this list of conditions and the following disclaimer in the documentation
  10. and/or other materials provided with the distribution.
  11. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  12. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  13. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  14. ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
  15. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  16. CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  17. SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  18. INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  19. CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  20. ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  21. POSSIBILITY OF SUCH DAMAGE.
  22. */
  23. #import "Reachability.h"
  24. #import <sys/socket.h>
  25. #import <netinet/in.h>
  26. #import <netinet6/in6.h>
  27. #import <arpa/inet.h>
  28. #import <ifaddrs.h>
  29. #import <netdb.h>
  30. NSString *const kReachabilityChangedNotification = @"kReachabilityChangedNotification";
  31. @interface Reachability ()
  32. @property (nonatomic, assign) SCNetworkReachabilityRef reachabilityRef;
  33. @property (nonatomic, strong) dispatch_queue_t reachabilitySerialQueue;
  34. @property (nonatomic, strong) id reachabilityObject;
  35. -(void)reachabilityChanged:(SCNetworkReachabilityFlags)flags;
  36. -(BOOL)isReachableWithFlags:(SCNetworkReachabilityFlags)flags;
  37. @end
  38. static NSString *reachabilityFlags(SCNetworkReachabilityFlags flags)
  39. {
  40. return [NSString stringWithFormat:@"%c%c %c%c%c%c%c%c%c",
  41. #if TARGET_OS_IPHONE
  42. (flags & kSCNetworkReachabilityFlagsIsWWAN) ? 'W' : '-',
  43. #else
  44. 'X',
  45. #endif
  46. (flags & kSCNetworkReachabilityFlagsReachable) ? 'R' : '-',
  47. (flags & kSCNetworkReachabilityFlagsConnectionRequired) ? 'c' : '-',
  48. (flags & kSCNetworkReachabilityFlagsTransientConnection) ? 't' : '-',
  49. (flags & kSCNetworkReachabilityFlagsInterventionRequired) ? 'i' : '-',
  50. (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) ? 'C' : '-',
  51. (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) ? 'D' : '-',
  52. (flags & kSCNetworkReachabilityFlagsIsLocalAddress) ? 'l' : '-',
  53. (flags & kSCNetworkReachabilityFlagsIsDirect) ? 'd' : '-'];
  54. }
  55. // Start listening for reachability notifications on the current run loop
  56. static void TMReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void* info)
  57. {
  58. #pragma unused (target)
  59. Reachability *reachability = ((__bridge Reachability*)info);
  60. // We probably don't need an autoreleasepool here, as GCD docs state each queue has its own autorelease pool,
  61. // but what the heck eh?
  62. @autoreleasepool
  63. {
  64. [reachability reachabilityChanged:flags];
  65. }
  66. }
  67. @implementation Reachability
  68. #pragma mark - Class Constructor Methods
  69. +(Reachability*)reachabilityWithHostName:(NSString*)hostname
  70. {
  71. return [Reachability reachabilityWithHostname:hostname];
  72. }
  73. +(Reachability*)reachabilityWithHostname:(NSString*)hostname
  74. {
  75. SCNetworkReachabilityRef ref = SCNetworkReachabilityCreateWithName(NULL, [hostname UTF8String]);
  76. if (ref)
  77. {
  78. id reachability = [[self alloc] initWithReachabilityRef:ref];
  79. return reachability;
  80. }
  81. return nil;
  82. }
  83. +(Reachability *)reachabilityWithAddress:(void *)hostAddress
  84. {
  85. SCNetworkReachabilityRef ref = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)hostAddress);
  86. if (ref)
  87. {
  88. id reachability = [[self alloc] initWithReachabilityRef:ref];
  89. return reachability;
  90. }
  91. return nil;
  92. }
  93. +(Reachability *)reachabilityForInternetConnection
  94. {
  95. struct sockaddr_in zeroAddress;
  96. bzero(&zeroAddress, sizeof(zeroAddress));
  97. zeroAddress.sin_len = sizeof(zeroAddress);
  98. zeroAddress.sin_family = AF_INET;
  99. return [self reachabilityWithAddress:&zeroAddress];
  100. }
  101. +(Reachability*)reachabilityForLocalWiFi
  102. {
  103. struct sockaddr_in localWifiAddress;
  104. bzero(&localWifiAddress, sizeof(localWifiAddress));
  105. localWifiAddress.sin_len = sizeof(localWifiAddress);
  106. localWifiAddress.sin_family = AF_INET;
  107. // IN_LINKLOCALNETNUM is defined in <netinet/in.h> as 169.254.0.0
  108. localWifiAddress.sin_addr.s_addr = htonl(IN_LINKLOCALNETNUM);
  109. return [self reachabilityWithAddress:&localWifiAddress];
  110. }
  111. // Initialization methods
  112. -(Reachability *)initWithReachabilityRef:(SCNetworkReachabilityRef)ref
  113. {
  114. self = [super init];
  115. if (self != nil)
  116. {
  117. self.reachableOnWWAN = YES;
  118. self.reachabilityRef = ref;
  119. // We need to create a serial queue.
  120. // We allocate this once for the lifetime of the notifier.
  121. self.reachabilitySerialQueue = dispatch_queue_create("com.tonymillion.reachability", NULL);
  122. }
  123. return self;
  124. }
  125. -(void)dealloc
  126. {
  127. [self stopNotifier];
  128. if(self.reachabilityRef)
  129. {
  130. CFRelease(self.reachabilityRef);
  131. self.reachabilityRef = nil;
  132. }
  133. self.reachableBlock = nil;
  134. self.unreachableBlock = nil;
  135. self.reachabilitySerialQueue = nil;
  136. }
  137. #pragma mark - Notifier Methods
  138. // Notifier
  139. // NOTE: This uses GCD to trigger the blocks - they *WILL NOT* be called on THE MAIN THREAD
  140. // - In other words DO NOT DO ANY UI UPDATES IN THE BLOCKS.
  141. // INSTEAD USE dispatch_async(dispatch_get_main_queue(), ^{UISTUFF}) (or dispatch_sync if you want)
  142. -(BOOL)startNotifier
  143. {
  144. // allow start notifier to be called multiple times
  145. if(self.reachabilityObject && (self.reachabilityObject == self))
  146. {
  147. return YES;
  148. }
  149. SCNetworkReachabilityContext context = { 0, NULL, NULL, NULL, NULL };
  150. context.info = (__bridge void *)self;
  151. if(SCNetworkReachabilitySetCallback(self.reachabilityRef, TMReachabilityCallback, &context))
  152. {
  153. // Set it as our reachability queue, which will retain the queue
  154. if(SCNetworkReachabilitySetDispatchQueue(self.reachabilityRef, self.reachabilitySerialQueue))
  155. {
  156. // this should do a retain on ourself, so as long as we're in notifier mode we shouldn't disappear out from under ourselves
  157. // woah
  158. self.reachabilityObject = self;
  159. return YES;
  160. }
  161. else
  162. {
  163. #ifdef DEBUG
  164. NSLog(@"SCNetworkReachabilitySetDispatchQueue() failed: %s", SCErrorString(SCError()));
  165. #endif
  166. // UH OH - FAILURE - stop any callbacks!
  167. SCNetworkReachabilitySetCallback(self.reachabilityRef, NULL, NULL);
  168. }
  169. }
  170. else
  171. {
  172. #ifdef DEBUG
  173. NSLog(@"SCNetworkReachabilitySetCallback() failed: %s", SCErrorString(SCError()));
  174. #endif
  175. }
  176. // if we get here we fail at the internet
  177. self.reachabilityObject = nil;
  178. return NO;
  179. }
  180. -(void)stopNotifier
  181. {
  182. // First stop, any callbacks!
  183. SCNetworkReachabilitySetCallback(self.reachabilityRef, NULL, NULL);
  184. // Unregister target from the GCD serial dispatch queue.
  185. SCNetworkReachabilitySetDispatchQueue(self.reachabilityRef, NULL);
  186. self.reachabilityObject = nil;
  187. }
  188. #pragma mark - reachability tests
  189. // This is for the case where you flick the airplane mode;
  190. // you end up getting something like this:
  191. //Reachability: WR ct-----
  192. //Reachability: -- -------
  193. //Reachability: WR ct-----
  194. //Reachability: -- -------
  195. // We treat this as 4 UNREACHABLE triggers - really apple should do better than this
  196. #define testcase (kSCNetworkReachabilityFlagsConnectionRequired | kSCNetworkReachabilityFlagsTransientConnection)
  197. -(BOOL)isReachableWithFlags:(SCNetworkReachabilityFlags)flags
  198. {
  199. BOOL connectionUP = YES;
  200. if(!(flags & kSCNetworkReachabilityFlagsReachable))
  201. connectionUP = NO;
  202. if( (flags & testcase) == testcase )
  203. connectionUP = NO;
  204. #if TARGET_OS_IPHONE
  205. if(flags & kSCNetworkReachabilityFlagsIsWWAN)
  206. {
  207. // We're on 3G.
  208. if(!self.reachableOnWWAN)
  209. {
  210. // We don't want to connect when on 3G.
  211. connectionUP = NO;
  212. }
  213. }
  214. #endif
  215. return connectionUP;
  216. }
  217. -(BOOL)isReachable
  218. {
  219. SCNetworkReachabilityFlags flags;
  220. if(!SCNetworkReachabilityGetFlags(self.reachabilityRef, &flags))
  221. return NO;
  222. return [self isReachableWithFlags:flags];
  223. }
  224. -(BOOL)isReachableViaWWAN
  225. {
  226. #if TARGET_OS_IPHONE
  227. SCNetworkReachabilityFlags flags = 0;
  228. if(SCNetworkReachabilityGetFlags(self.reachabilityRef, &flags))
  229. {
  230. // Check we're REACHABLE
  231. if(flags & kSCNetworkReachabilityFlagsReachable)
  232. {
  233. // Now, check we're on WWAN
  234. if(flags & kSCNetworkReachabilityFlagsIsWWAN)
  235. {
  236. return YES;
  237. }
  238. }
  239. }
  240. #endif
  241. return NO;
  242. }
  243. -(BOOL)isReachableViaWiFi
  244. {
  245. SCNetworkReachabilityFlags flags = 0;
  246. if(SCNetworkReachabilityGetFlags(self.reachabilityRef, &flags))
  247. {
  248. // Check we're reachable
  249. if((flags & kSCNetworkReachabilityFlagsReachable))
  250. {
  251. #if TARGET_OS_IPHONE
  252. // Check we're NOT on WWAN
  253. if((flags & kSCNetworkReachabilityFlagsIsWWAN))
  254. {
  255. return NO;
  256. }
  257. #endif
  258. return YES;
  259. }
  260. }
  261. return NO;
  262. }
  263. // WWAN may be available, but not active until a connection has been established.
  264. // WiFi may require a connection for VPN on Demand.
  265. -(BOOL)isConnectionRequired
  266. {
  267. return [self connectionRequired];
  268. }
  269. -(BOOL)connectionRequired
  270. {
  271. SCNetworkReachabilityFlags flags;
  272. if(SCNetworkReachabilityGetFlags(self.reachabilityRef, &flags))
  273. {
  274. return (flags & kSCNetworkReachabilityFlagsConnectionRequired);
  275. }
  276. return NO;
  277. }
  278. // Dynamic, on demand connection?
  279. -(BOOL)isConnectionOnDemand
  280. {
  281. SCNetworkReachabilityFlags flags;
  282. if (SCNetworkReachabilityGetFlags(self.reachabilityRef, &flags))
  283. {
  284. return ((flags & kSCNetworkReachabilityFlagsConnectionRequired) &&
  285. (flags & (kSCNetworkReachabilityFlagsConnectionOnTraffic | kSCNetworkReachabilityFlagsConnectionOnDemand)));
  286. }
  287. return NO;
  288. }
  289. // Is user intervention required?
  290. -(BOOL)isInterventionRequired
  291. {
  292. SCNetworkReachabilityFlags flags;
  293. if (SCNetworkReachabilityGetFlags(self.reachabilityRef, &flags))
  294. {
  295. return ((flags & kSCNetworkReachabilityFlagsConnectionRequired) &&
  296. (flags & kSCNetworkReachabilityFlagsInterventionRequired));
  297. }
  298. return NO;
  299. }
  300. #pragma mark - reachability status stuff
  301. -(NetworkStatus)currentReachabilityStatus
  302. {
  303. if([self isReachable])
  304. {
  305. if([self isReachableViaWiFi])
  306. return ReachableViaWiFi;
  307. #if TARGET_OS_IPHONE
  308. return ReachableViaWWAN;
  309. #endif
  310. }
  311. return NotReachable;
  312. }
  313. -(SCNetworkReachabilityFlags)reachabilityFlags
  314. {
  315. SCNetworkReachabilityFlags flags = 0;
  316. if(SCNetworkReachabilityGetFlags(self.reachabilityRef, &flags))
  317. {
  318. return flags;
  319. }
  320. return 0;
  321. }
  322. -(NSString*)currentReachabilityString
  323. {
  324. NetworkStatus temp = [self currentReachabilityStatus];
  325. if(temp == ReachableViaWWAN)
  326. {
  327. // Updated for the fact that we have CDMA phones now!
  328. return NSLocalizedString(@"Cellular", @"");
  329. }
  330. if (temp == ReachableViaWiFi)
  331. {
  332. return NSLocalizedString(@"WiFi", @"");
  333. }
  334. return NSLocalizedString(@"No Connection", @"");
  335. }
  336. -(NSString*)currentReachabilityFlags
  337. {
  338. return reachabilityFlags([self reachabilityFlags]);
  339. }
  340. #pragma mark - Callback function calls this method
  341. -(void)reachabilityChanged:(SCNetworkReachabilityFlags)flags
  342. {
  343. if([self isReachableWithFlags:flags])
  344. {
  345. if(self.reachableBlock)
  346. {
  347. self.reachableBlock(self);
  348. }
  349. }
  350. else
  351. {
  352. if(self.unreachableBlock)
  353. {
  354. self.unreachableBlock(self);
  355. }
  356. }
  357. // this makes sure the change notification happens on the MAIN THREAD
  358. dispatch_async(dispatch_get_main_queue(), ^{
  359. [[NSNotificationCenter defaultCenter] postNotificationName:kReachabilityChangedNotification
  360. object:self];
  361. });
  362. }
  363. #pragma mark - Debug Description
  364. - (NSString *) description
  365. {
  366. NSString *description = [NSString stringWithFormat:@"<%@: %#x (%@)>",
  367. NSStringFromClass([self class]), (unsigned int) self, [self currentReachabilityFlags]];
  368. return description;
  369. }
  370. @end