1. Import Systemconfiguration.framework, and #import<systemconfiguration/scnetworkreachability.h>
+(BOOL) connectedtonetwork{//Create 0 address, 0.0.0.0 address indicates the network connection status of the query native structSockaddr_storage zeroaddress;//IP Addressbzero (&zeroaddress,sizeof(zeroaddress));//convert address to 0.0.0.0Zeroaddress.ss_len =sizeof(zeroaddress);//Address Lengthzeroaddress.ss_family = af_inet;//The address type is UDP, TCP, etc. //Recover reachability FlagsScnetworkreachabilityref defaultroutereachability = scnetworkreachabilitycreatewithaddress (NULL, (structSOCKADDR *) &zeroaddress); Scnetworkreachabilityflags flags; //get a connection flagBOOL didretrieveflags = Scnetworkreachabilitygetflags (defaultroutereachability, &flags); Cfrelease (defaultroutereachability); //If you cannot get the connection flag, you cannot connect to the network and return directly if(!didretrieveflags) { returnNO; } //Judging by the connection marks obtainedBOOL isreachable= Flags &kscnetworkflagsreachable; BOOL needsconnection= Flags &kscnetworkflagsconnectionrequired; return(isreachable&&!needsconnection)?Yes:no; /*1, Sockaddr_storage This structure stores socket address information. Because This structure are large enough to store IPv4 or IPV6 address information, it use promotes protocol-family and pro Tocol-version independence, and simplifies cross-platform development. Use this structure the the SOCKADDR structure. 2, extern void bzero (void *s, int n); Usage: #include <string.h> function: The first n bytes of the byte string s are zero and include ' + '. Description: Bzero has no return value, and using the String.h header file, String.h was once part of the POSIX standard, but within the posix.1-2001 standard, these functions were flagged for legacy functions and are not recommended for use. These functions are not already in the posix.1-2008 standard. It is recommended to use memset instead of bzero. Bzero (&TT, sizeof (TT)); Equivalent to memset (&tt,0,sizeof (TT)); Bzero (S, 20); Equivalent to memset (s,0,20); */}
2. Request a network using a third-party class library,
#import "Reachability.h"
-(BOOL) isconnectionavailable{BOOL isexistencenetwork=YES; Reachability*reach = [reachability reachabilitywithhostname:@"http://www.baidu.com"]; Switch([reach Currentreachabilitystatus]) { Casenotreachable:isexistencenetwork=NO; //NSLog (@ "notreachable"); Break; Casereachableviawifi:isexistencenetwork=YES; //NSLog (@ "WIFI"); Break; Casereachableviawwan:isexistencenetwork=YES; //NSLog (@ "3G"); Break; } returnisexistencenetwork;}
iOS to determine if the device is networked