How to write a simple Ping method in Cocoa/Objective-C

前端 未结 7 761
一向
一向 2020-11-29 00:52

I need to write a simple ping method in Cocoa/Objective-C. It also needs to work on the iPhone.

I found an example that uses icmp, will thi

7条回答
  •  野性不改
    2020-11-29 01:22

    Let me try this again...this time logging in, and formatting better ;-)

    StreamSCNetworkCheckReachabilityByName is deprecated and NOT available for the iPhone.

    bool success = false;
    const char *host_name = [@"stackoverflow.com" 
                             cStringUsingEncoding:NSASCIIStringEncoding];
    
    SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL,
                                                                            host_name);
    SCNetworkReachabilityFlags flags;
    success = SCNetworkReachabilityGetFlags(reachability, &flags);
    
    //prevents memory leak per Carlos Guzman's comment
    CFRelease(reachability);
    
    bool isAvailable = success && (flags & kSCNetworkFlagsReachable) && 
                                 !(flags & kSCNetworkFlagsConnectionRequired);
    if (isAvailable) {
        NSLog(@"Host is reachable: %d", flags);
    }else{
        NSLog(@"Host is unreachable");
    }
    

    Note: SystemConfiguration.framework is required

提交回复
热议问题