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:

Test If A Host Is Active
1
2
3
4
5
6
7
8
9
10
11
12
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");
}

Comments