首页 > 代码库 > 检测网络是否有效
检测网络是否有效
//检测网络是否有效- (BOOL) checkNetworkIsValid { struct sockaddr_in zeroAddress; bzero(&zeroAddress, sizeof(zeroAddress)); zeroAddress.sin_len = sizeof(zeroAddress); zeroAddress.sin_family = AF_INET; SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress); SCNetworkReachabilityFlags flags; BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags); CFRelease(defaultRouteReachability); if (!didRetrieveFlags) { return NO; } BOOL isReachable = flags & kSCNetworkFlagsReachable; BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired; // = flags & kSCNetworkReachabilityFlagsIsWWAN; BOOL nonWifi = flags & kSCNetworkReachabilityFlagsTransientConnection; BOOL moveNet = flags & kSCNetworkReachabilityFlagsIsWWAN; return ((isReachable && !needsConnection) || nonWifi || moveNet) ? YES : NO;}
#import "CheckNetwork.h"#import <netinet/in.h>#import <SystemConfiguration/SCNetworkReachability.h>@implementation CheckNetwork+ (BOOL) connectedToNetwork{ //创建零地址,0.0.0.0的地址表示查询本机的网络连接状态 struct sockaddr_in zeroAddress; bzero(&zeroAddress, sizeof(zeroAddress)); zeroAddress.sin_len = sizeof(zeroAddress); zeroAddress.sin_family = AF_INET; // Recover reachability flags SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress); SCNetworkReachabilityFlags flags; //获得连接的标志 BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags); CFRelease(defaultRouteReachability); //如果不能获取连接标志,则不能连接网络,直接返回 if (!didRetrieveFlags) { return NO; } //根据获得的连接标志进行判断 BOOL isReachable = flags & kSCNetworkFlagsReachable; BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired; BOOL isWWAN = flags & kSCNetworkReachabilityFlagsIsWWAN; return (isReachable && (!needsConnection || isWWAN)) ? YES : NO;}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。