1 //判断网络是否连接 2 + (BOOL) connectedToNetwork 3 { 4 //创建零地址,0.0.0.0的地址表示查询本机的网络连接状态 5 struct sockaddr_in zeroAddress; //struct用来向方法中传递复杂的参数(把参数当作对象,这样便于扩展) 6 bzero(&zeroAddress, sizeof(zeroAddress)); 7 zeroAddress.sin_len = sizeof(zeroAddress); 8 zeroAddress.sin_family = AF_INET; 9 10 // Recover reachability flags 11 SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress); 12 SCNetworkReachabilityFlags flags; 13 //获得连接的标志 14 BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags); 15 CFRelease(defaultRouteReachability); 16 //如果不能获取连接标志,则不能连接网络,直接返回 17 if (!didRetrieveFlags) 18 { 19 return NO; 20 } 21 //根据获得的连接标志进行判断 22 BOOL isReachable = flags & kSCNetworkFlagsReachable; 23 BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired; 24 BOOL isWWAN = flags & kSCNetworkReachabilityFlagsIsWWAN; 25 return (isReachable && (!needsConnection || isWWAN)) ? YES : NO; 26 }
时间: 2024-10-21 09:44:41