project_files/HedgewarsMobile/Classes/HWUtils.m
changeset 6246 6b2d19ed521a
parent 6209 074ab6ebcb3e
child 6247 6dfad55fd71c
--- a/project_files/HedgewarsMobile/Classes/HWUtils.m	Sun Oct 30 23:24:36 2011 +0100
+++ b/project_files/HedgewarsMobile/Classes/HWUtils.m	Mon Oct 31 01:44:32 2011 +0100
@@ -22,6 +22,8 @@
 #import "HWUtils.h"
 #import <sys/types.h>
 #import <sys/sysctl.h>
+#import <netinet/in.h>
+#import <SystemConfiguration/SCNetworkReachability.h>
 #import "hwconsts.h"
 
 static NSString *cachedModel = nil;
@@ -60,6 +62,46 @@
     return cachedColors;
 }
 
++(NSInteger) randomPort {
+    srandom(time(NULL));
+    NSInteger res = (random() % 64511) + 1024;
+    return (res == NETGAME_DEFAULT_PORT) ? [HWUtils randomPort] : res;
+}
+
++(BOOL) isNetworkReachable {
+    // Create zero addy
+    struct sockaddr_in zeroAddress;
+    bzero(&zeroAddress, sizeof(zeroAddress));
+    zeroAddress.sin_len = sizeof(zeroAddress);
+    zeroAddress.sin_family = AF_INET;
+
+    // Recover reachability flags
+    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
+    SCNetworkReachabilityFlags flags;
+
+    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
+    CFRelease(defaultRouteReachability);
+
+    if (!didRetrieveFlags) {
+        NSLog(@"Error. Could not recover network reachability flags");
+        return NO;
+    }
+
+    BOOL isReachable = flags & kSCNetworkFlagsReachable;
+    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
+    BOOL nonWiFi = flags & kSCNetworkReachabilityFlagsTransientConnection;
+
+    NSURL *testURL = [NSURL URLWithString:@"http://www.apple.com/"];
+    NSURLRequest *testRequest = [NSURLRequest requestWithURL:testURL
+                                                 cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
+                                             timeoutInterval:20.0];
+    NSURLConnection *testConnection = [[NSURLConnection alloc] initWithRequest:testRequest delegate:nil];
+    BOOL testResult = testConnection ? YES : NO;
+    [testConnection release];
+
+    return ((isReachable && !needsConnection) || nonWiFi) ? testResult : NO;
+}
+
 +(void) releaseCache {
     releaseAndNil(cachedModel);
     releaseAndNil(cachedColors);