iOS 如何获取手机外网IP地址(附内网IP地址)

来源:互联网 发布:淘宝店铺0信誉出售 编辑:程序博客网 时间:2024/05/17 02:56

转自:http://blog.csdn.net/txz_gray/article/details/53217293


查找了一些方法,最初以为拿到的就是手机对外的公网地址,其实只是本地IP地址。下面把获取手机内外网IP地址的方法总结下:

一、获取手机本地静态IP地址:(局域网)

方法1:

首先导入头文件:

[objc] view plain copy
  1. //IP地址需求库  
  2. #import <sys/socket.h>  
  3. #import <sys/sockio.h>  
  4. #import <sys/ioctl.h>  
  5. #import <net/if.h>  
  6. #import <arpa/inet.h>  
具体方法:

[objc] view plain copy
  1. //获取设备IP地址  
  2. -(NSString *)getDeviceIPAddresses  
  3. {  
  4.     int sockfd = socket(AF_INET,SOCK_DGRAM, 0);  
  5.     // if (sockfd <</span> 0) return nil; //这句报错,由于转载的,不太懂,注释掉无影响,懂的大神欢迎指导  
  6.     NSMutableArray *ips = [NSMutableArray array];  
  7.   
  8.     int BUFFERSIZE =4096;  
  9.       
  10.     struct ifconf ifc;  
  11.       
  12.     char buffer[BUFFERSIZE], *ptr, lastname[IFNAMSIZ], *cptr;  
  13.       
  14.     struct ifreq *ifr, ifrcopy;  
  15.       
  16.     ifc.ifc_len = BUFFERSIZE;  
  17.       
  18.     ifc.ifc_buf = buffer;  
  19.       
  20.     if (ioctl(sockfd,SIOCGIFCONF, &ifc) >= 0){  
  21.           
  22.         for (ptr = buffer; ptr < buffer + ifc.ifc_len; ){  
  23.               
  24.             ifr = (struct ifreq *)ptr;  
  25.               
  26.             int len =sizeof(struct sockaddr);  
  27.               
  28.             if (ifr->ifr_addr.sa_len > len) {  
  29.                 len = ifr->ifr_addr.sa_len;  
  30.             }  
  31.               
  32.             ptr += sizeof(ifr->ifr_name) + len;  
  33.               
  34.             if (ifr->ifr_addr.sa_family !=AF_INET) continue;  
  35.               
  36.             if ((cptr = (charchar *)strchr(ifr->ifr_name,':')) != NULL) *cptr =0;  
  37.               
  38.             if (strncmp(lastname, ifr->ifr_name,IFNAMSIZ) == 0)continue;  
  39.               
  40.             memcpy(lastname, ifr->ifr_name,IFNAMSIZ);  
  41.               
  42.             ifrcopy = *ifr;  
  43.               
  44.             ioctl(sockfd,SIOCGIFFLAGS, &ifrcopy);  
  45.               
  46.             if ((ifrcopy.ifr_flags &IFF_UP) == 0)continue;  
  47.   
  48.             NSString *ip = [NSString stringWithFormat:@"%s",inet_ntoa(((struct sockaddr_in *)&ifr->ifr_addr)->sin_addr)];  
  49.             [ips addObject:ip];  
  50.         }  
  51.     }  
  52.     close(sockfd);  
  53.   
  54.     NSString *deviceIP =@"";  
  55.       
  56.     for (int i=0; i < ips.count; i++){  
  57.         if (ips.count >0){  
  58.             deviceIP = [NSString stringWithFormat:@"%@",ips.lastObject];  
  59.         }  
  60.     }  
  61.       
  62.     return deviceIP;  
  63. }  

参考:http://blog.sina.com.cn/s/blog_b0b335e20102y3im.html


方法2:

导入两个头文件,此法只能获取到WiFi环境下的本地IP,比较简洁

[objc] view plain copy
  1. #import <ifaddrs.h>  
  2. #import <arpa/inet.h>  
[objc] view plain copy
  1. + (NSString *)deviceIPAdress {  
  2.     NSString *address = @"手机移动网络";  
  3.     struct ifaddrs *interfaces = NULL;  
  4.     struct ifaddrs *temp_addr = NULL;  
  5.     int success = 0;  
  6.       
  7.     success = getifaddrs(&interfaces);  
  8.     if (success == 0) {  
  9.         temp_addr = interfaces;  
  10.         while (temp_addr != NULL) {  
  11.             if( (*temp_addr).ifa_addr->sa_family == AF_INET) {  
  12.                 if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {  
  13.                     address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];  
  14.                 }  
  15.             }  
  16.               
  17.             temp_addr = temp_addr->ifa_next;  
  18.         }  
  19.     }  
  20.     freeifaddrs(interfaces);  
  21.       
  22.     //    NSLog(@"手机的IP是:%@", address);  
  23.       
  24.     return address;  
  25. }  


二、获取手机外网IP(公网IP)

网上找了很久获取外网IP的方法,很多访问网址已经不能用了,能用的主要有2个,但是获取到的IP地址不同,下面详细介绍。

首推方法1:此方法采用的淘宝网址,获取的到IP与百度IP是一样的,考虑到如今百度横行,所以我使用的是此方法。

[objc] view plain copy
  1. -(NSString *)deviceWANIPAddress  
  2. {  
  3.     NSURL *ipURL = [NSURL URLWithString:@"http://ip.taobao.com/service/getIpInfo.php?ip=myip"];  
  4.     NSData *data = [NSData dataWithContentsOfURL:ipURL];  
  5.     NSDictionary *ipDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
  
  6.     NSString *ipStr = nil;  
  7.     if (ipDic && [ipDic[@"code"] integerValue] == 0) { //获取成功  
  8.         ipStr = ipDic[@"data"][@"ip"];  
  9.     }  
  10.     return (ipStr ? ipStr : @"");  
  11. }  

访问接口返回的json数据


百度ip查到的本机ip:



方法2:此方法访问的搜狐的获取ip接口,返回的IP与百度淘宝不一样。(可能是此接口精确到了具体的区。。。)

[objc] view plain copy
  1. -(NSString *)getWANIPAddress  
  2. {  
  3.     NSError *error;  
  4.     NSURL *ipURL = [NSURL URLWithString:@"http://pv.sohu.com/cityjson?ie=utf-8"];  
  5.       
  6.     NSMutableString *ip = [NSMutableString stringWithContentsOfURL:ipURL encoding:NSUTF8StringEncoding error:&error];  
  7.     //判断返回字符串是否为所需数据  
  8.     if ([ip hasPrefix:@"var returnCitySN = "]) {  
  9.         //对字符串进行处理,然后进行json解析  
  10.         //删除字符串多余字符串  
  11.         NSRange range = NSMakeRange(019);  
  12.         [ip deleteCharactersInRange:range];  
  13.         NSString * nowIp =[ip substringToIndex:ip.length-1];  
  14.         //将字符串转换成二进制进行Json解析  
  15.         NSData * data = [nowIp dataUsingEncoding:NSUTF8StringEncoding];  
  16.         NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];  
  17.         NSLog(@"%@",dict);  
  18.         return dict[@"cip"] ? dict[@"cip"] : @"";  
  19.     }  
  20.     return @"";  
  21. }  

访问接口取到的数据:


参考:http://blog.csdn.net/henry_moneybag/article/details/51463375

还有一个接口可直接获取到IP,但返回比较慢,可能返回失败,不推荐。

[objc] view plain copy
  1. NSError *error;  
  2. NSURL *ipURL = [NSURL URLWithString:@"http://ifconfig.me/ip"];  
  3. NSString *ip = [NSString stringWithContentsOfURL:ipURL encoding:NSUTF8StringEncoding error:&error]; 

原创粉丝点击