Next Spaceship

Driving into future...

How to Test if a Host Is Active

| Comments

Sometimes, we would like to check if a remote host is reachable before we establish a connection. This is much like the function of the ping command in terminal. Well in Cocoa programing, you can use the function SCNetworkReachabilityCreateWithName().

Here is the code:

objc Test If A Host Is Active bool success = false; const char *host_name = [ip cStringUsingEncoding:NSASCIIStringEncoding]; SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, host_name); SCNetworkConnectionFlags flags; success = SCNetworkReachabilityGetFlags(reachability, &flags); bool isAvailable = success && (flags & kSCNetworkFlagsReachable) && !(flags & kSCNetworkFlagsConnectionRequired);if (isAvailable) { NSLog(@"Host is reachable: %d", flags); } else { NSLog(@"Host is unreachable"); }