检查IPhone网络链接状态

 将解压后的文件导入到项目中:
 
执行程序:
//
//  NetWorkStata.h
//  SnowPro
//
//  Created by Lcjiang478 on 12-9-12.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//
//
//  NetWorkStata.m
//  SnowPro
//
//  Created by Lcjiang478 on 12-9-12.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "NetWorkStata.h"

#import <SystemConfiguration/SystemConfiguration.h> 
 // 须要事先导入SystemConfiguration.framework

#import <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>

@implementation NetWorkStata


+ (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;
    return (isReachable && !needsConnection) ? YES : NO;  
}@end 

#import <Foundation/Foundation.h> interface NetWorkStata : NSObject + (BOOL) connectedToNetwork;@end
 
相关文章
相关标签/搜索