To get the device's IP address, a random search on the internet can find a lot of results, but these can be found in the code is basically written in C, and did not target iOS optimized adjustment, use is not convenient. Just to get the IP address, encapsulated in a function called and then used to be convenient. The code is relatively simple, that is, the online copy of the code to do the collation and iOS adaptation. function returns an array that contains the IP address of all network adapters.
The code is as follows |
Copy Code |
-(Nsarray *) getipaddresses { int SOCKFD = socket (af_inet, SOCK_DGRAM, 0); if (SOCKFD < 0) return nil; Nsmutablearray *ips = [Nsmutablearray array];
int buffersize = 4096; struct ifconf ifc; Char Buffer[buffersize], *ptr, Lastname[ifnamsiz], *cptr; struct Ifreq *ifr, ifrcopy; Ifc.ifc_len = buffersize; ifc.ifc_buf = buffer; if (IOCTL (SOCKFD, siocgifconf, &IFC) >= 0) { for (ptr = buffer; ptr < buffer + Ifc.ifc_len;) { IFR = (struct ifreq *) ptr; int len = sizeof (struct sockaddr); if (Ifr->ifr_addr.sa_len > Len) { Len = ifr->ifr_addr.sa_len; } PTR + + sizeof (ifr->ifr_name) + len; if (ifr->ifr_addr.sa_family!= af_inet) continue; if ((cptr = (char *) STRCHR (ifr->ifr_name, ': '))!= NULL) *cptr = 0; if (strncmp (LastName, Ifr->ifr_name, ifnamsiz) = = 0) continue; memcpy (LastName, Ifr->ifr_name, Ifnamsiz); Ifrcopy = *IFR; IOCTL (SOCKFD, Siocgifflags, &ifrcopy); if ((Ifrcopy.ifr_flags & iff_up) = = 0) continue;
NSString *ip = [nsstring stringwithformat:@ '%s ', Inet_ntoa ((struct sockaddr_in *) &ifr->ifr_addr) )]; [IPs ADDOBJECT:IP]; } } Close (SOCKFD); return IPs; } |
File headers need to add these import
The code is as follows |
Copy Code |
#import <sys/socket.h> #import <sys/sockio.h> #import <sys/ioctl.h> #import <net/if.h> #import <arpa/inet.h> |
The second method is to get the public network IP
code is as follows |
copy code |
-(void) Getcurrentip { nsurl *url = [Nsurl urlwithstring:@] http:/ /automation.whatismyip.com/n09230945.asp "]; __block asihttprequest *request = [ASIHTTPRequest Requestwithurl:url]; [request setcompletionblock:^{ nsstring *responsestring = [request responsestring]; if (responsestring) { nsstring *ip = [NSString stringwithformat:@ "%@", responsestring]; nslog (@ "responsestring =%@", IP); }]; [request setfailedblock:^{ }]; } |
The
ASIHTTPRequest the Open Source library for this network.