需要先加入 SystemConfiguration.framework
frameworks:/System/Library/Frameworks/SystemConfiguration.framework
头文件:
#import <sys/socket.h>
#import <netinet/in.h>
#import <arpa/inet.h>
#import <netdb.h>
#import<SystemConfiguration/SCNetworkReachability.h>
- (BOOL) connectedToNetwork
{
//Create zero addy
structsockaddr_in zeroAddress;
bzero(&zeroAddress,sizeof(zeroAddress));
zeroAddress.sin_len= sizeof(zeroAddress);
zeroAddress.sin_family= AF_INET;
//Recover reachability flags
SCNetworkReachabilityRefdefaultRouteReachability =SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr*)&zeroAddress);
SCNetworkReachabilityFlagsflags;
BOOLdidRetrieveFlags =SCNetworkReachabilityGetFlags(defaultRouteReachability,&flags);
CFRelease(defaultRouteReachability);
if(!didRetrieveFlags)
{
returnNO;
}
BOOLisReachable = flags &kSCNetworkFlagsReachable;
BOOLneedsConnection = flags &kSCNetworkFlagsConnectionRequired;
return(isReachable && !needsConnection) ?YES : NO;
}