project_files/HedgewarsMobile/Classes/ServerSetup.m
changeset 6078 8c0cc07731e5
parent 5483 fc755bb8096d
--- a/project_files/HedgewarsMobile/Classes/ServerSetup.m	Fri Sep 30 22:33:28 2011 -0400
+++ b/project_files/HedgewarsMobile/Classes/ServerSetup.m	Sun Oct 02 00:57:04 2011 +0200
@@ -20,8 +20,9 @@
 
 
 #import "ServerSetup.h"
-#import "PascalImports.h"
-#import "CommodityFunctions.h"
+#import <netinet/in.h>
+#import <SystemConfiguration/SCNetworkReachability.h>
+
 #import "hwconsts.h"
 
 #define BUFFER_SIZE 256
@@ -29,6 +30,47 @@
 @implementation ServerSetup
 @synthesize systemSettings;
 
+
++(NSInteger) randomPort {
+    srandom(time(NULL));
+    NSInteger res = (random() % 64511) + 1024;
+    return (res == NETGAME_DEFAULT_PORT) ? [ServerSetup 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;
+}
+
 -(id) init {
     if (self = [super init]) {
         self.systemSettings = nil; //nsuserdefault