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

前端 未结 7 765
一向
一向 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:23

    The answer Gene Myers posted works using "SCNetworkReachabilityCreateWithName" for me - but only in the simulator. On my device (iPod w/OS 2.2.1) it always returns "Host is reachable" even for nonsense addresses like "zzz".

    Am I misunderstanding something? Thanks.

    Here's my code just in case:

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

        - (IBAction) TestReachability:(id)sender
    {
        bool success = false;
        const char *host_name = [ipAddressText.textcStringUsingEncoding:NSASCIIStringEncoding];
        NSString *imageConnectionSuccess = @"Connected.png";
        NSString *imageConnectionFailed = @"NotConnected.png";
    
        SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL,
                                                                                    host_name);
        SCNetworkReachabilityFlags flags;
        success = SCNetworkReachabilityGetFlags(reachability, &flags);
        bool isAvailable = success && (flags & kSCNetworkFlagsReachable) && 
            !(flags & kSCNetworkFlagsConnectionRequired);
        if (isAvailable)
        {
            NSLog([NSString stringWithFormat: @"'%s' is reachable, flags: %x", host_name, flags]);
            [imageView setImage: [UIImage imageNamed:imageConnectionSuccess]]; 
        }
        else
        {
            NSLog([NSString stringWithFormat: @"'%s' is not reachable", host_name]);
            [imageView setImage: [UIImage imageNamed:imageConnectionFailed]]; 
        }
    }
    

提交回复
热议问题