要獲取設備的IP地址,網上隨便一搜就能找到一大堆結果,但是這些能找到的代碼基本上都是用C寫的,並沒有針對iOS做過優化調整,使用起來也不方便。就只是要獲取IP地址而已,封裝成一個函數調用一下然後使用起來才方便。代碼比較簡單,就是把網上抄來的代碼做了整理和iOS適配。函數返回一個包含了所有網卡的IP地址的一個數組。
代碼如下 復制代碼- (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)->sin_addr)];
[ips addObject:ip];
}
}
close(sockfd);
return ips;
}
文件頭部需要加上這些import
代碼如下 復制代碼#import <sys/socket.h>
#import <sys/sockio.h>
#import <sys/ioctl.h>
#import <net/if.h>
#import <arpa/inet.h>
第二種方法是可以獲取公網ip
- (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:^{
}];
}
用到了ASIHTTPRequest這個網絡開源庫。