无法检查特定ip地址的可达性.任何MAC框架都支持这一点吗



我遵循的步骤1) 添加了系统配置框架并导入#import"systemconfiguration/scnetworkreachability.h",然后添加了以下用于检查连接的代码

BOOL hasLeadingNumberInString(NSString* s) {
  if(s)
      return [s length] && isnumber([s characterAtIndex:0]);
else
    return NO;
}
-(BOOL)networkConnected: (NSString *)ipAdress  {
    SCNetworkReachabilityFlags  flags = 0;
    SCNetworkReachabilityRef    netReachability;
    BOOL                        retrievedFlags = NO;
    // added the "if" and first part of if statement
    //
    if (hasLeadingNumberInString(ipAdress)) {
        struct sockaddr_in the_addr;
        memset((void *)&the_addr, 0, sizeof(the_addr));
        the_addr.sin_family = AF_INET;
        the_addr.sin_len = sizeof(the_addr);
        const char* server_addr = [ipAdress UTF8String];
        unsigned long ip_addr = inet_addr(server_addr);
        the_addr.sin_addr.s_addr = ip_addr;
        netReachability =    SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr*)&the_addr);
    } else {
        netReachability = SCNetworkReachabilityCreateWithName(NULL, [ipAdress UTF8String]);
    }
    if (netReachability) {
        retrievedFlags = SCNetworkReachabilityGetFlags(netReachability, &flags);
        CFRelease(netReachability);
    }
    if (!retrievedFlags || !flags) {
        return NO;
    }
    return YES;
}
- (void)checkconnectivity
{
    if([self networkConnected:@"192.168.2.10" ])
        NSLog(@"Connected");
    else
         NSLog(@"Not Connected");
}

看在上帝的份上,它总是连接的。

方法2,我使用cocopods添加了AFnetworking。我导入了"AFNetworkReachabilityManager.h"文件并使用了managerforaddress,它总是返回未知的

 AFNetworkReachabilityManager *addressCheck=[AFNetworkReachabilityManager managerForAddress:@"192.168.3.10"];
   [addressCheck startMonitoring];
    [addressCheck setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
    }];
    NSLog(@"%hhd",addressCheck.reachable);
    NSLog(@"%hhd",[addressCheck isReachable]);
    NSString *str=[[NSString alloc]initWithString:[addressCheck localizedNetworkReachabilityStatusString]];
    NSLog(@"%@",str);
    NSLog(@"%@",addressCheck.localizedNetworkReachabilityStatusString);
}

即使这样,我也无法获得特定地址的连接。有没有办法得到这个,或者这是不可能的。

您只需使用Processping命令来检查ip地址是否可访问。

Swift 4示例:(仅限macOS

func ping(at ipAddress: String) -> Int32 {
    let process = Process.launchedProcess(launchPath: "/sbin/ping", arguments: ["-c1", ipAddress])
    process.waitUntilExit()
    return process.terminationStatus
}
let reachable = ping(at: "10.0.1.119") == 0

相关内容

  • 没有找到相关文章

最新更新