ios 手机ip获取

2017-10-19  本文已影响0人  oc123

本文总结一下手机内外网ip获取的方法,来自:
http://blog.csdn.net/txz_gray/article/details/53217293
获取手机(局域网)本地静态IP地址:

  //导入IP地址需求库:
  #import <sys/socket.h> 
  #import <sys/sockio.h>  
  #import <sys/ioctl.h>
  #import <net/if.h> 
  #import <arpa/inet.h> 

ip获取函数:

 //获取IP地址  
-(NSString *)getDeviceIP  
{  
    int sockfd = socket(AF_INET,SOCK_DGRAM, 0);  
    // if (sockfd <</span> 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 = (charchar *)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);  
  
    NSString *deviceIP =@"";  
      
    for (int i=0; i < ips.count; i++){  
        if (ips.count >0){  
            deviceIP = [NSString stringWithFormat:@"%@",ips.lastObject];  
        }  
    }  
      
    return deviceIP;  
}  

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

获取WiFi下IP:

//导入依赖库
#import <ifaddrs.h> 
#import <arpa/inet.h>

调用函数:

  + (NSString *)deviceIPWithinWiFi {  
    NSString *address = @"手机移动网络";  
    struct ifaddrs *interfaces = NULL;  
    struct ifaddrs *temp_addr = NULL;  
    int success = 0;  
      
    success = getifaddrs(&interfaces);  
    if (success == 0) {  
        temp_addr = interfaces;  
        while (temp_addr != NULL) {  
            if( (*temp_addr).ifa_addr->sa_family == AF_INET) {  
                if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {  
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];  
                }  
            }  
              
            temp_addr = temp_addr->ifa_next;  
        }  
    }  
    freeifaddrs(interfaces);  
      
    //    NSLog(@"手机的IP是:%@", address);  
      
    return address;  
}  

获取手机(公网IP)外网IP:
获取方法一:

//获取的IP与百度得到的IP一样
-(NSString *)deviceWANIPAddress  
{  
    NSURL *ipURL = [NSURL URLWithString:@"http://ip.taobao.com/service/getIpInfo.php?ip=myip"];  
    NSData *data = [NSData dataWithContentsOfURL:ipURL];  
    NSDictionary *ipDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];  
    NSString *ipStr = nil;  
    if (ipDic && [ipDic[@"code"] integerValue] == 0) { //获取成功  
        ipStr = ipDic[@"data"][@"ip"];  
    }  
    return (ipStr ? ipStr : @"");  
}  

获取方法二:

//此方法访问的搜狐的获取ip接口,返回的IP与百度淘宝不一样(可能是此接口精确到了具体的区)
-(NSString *)getWANIPAddress  
{  
    NSError *error;  
    NSURL *ipURL = [NSURL URLWithString:@"http://pv.sohu.com/cityjson?ie=utf-8"];  
      
    NSMutableString *ip = [NSMutableString stringWithContentsOfURL:ipURL encoding:NSUTF8StringEncoding error:&error];  
    //判断返回字符串是否为所需数据  
    if ([ip hasPrefix:@"var returnCitySN = "]) {  
        //对字符串进行处理,然后进行json解析  
        //删除字符串多余字符串  
        NSRange range = NSMakeRange(0, 19);  
        [ip deleteCharactersInRange:range];  
        NSString * nowIp =[ip substringToIndex:ip.length-1];  
        //将字符串转换成二进制进行Json解析  
        NSData * data = [nowIp dataUsingEncoding:NSUTF8StringEncoding];  
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];  
        NSLog(@"%@",dict);  
        return dict[@"cip"] ? dict[@"cip"] : @"";  
    }  
    return @"";  
} 

不推荐的方法,可直接获取到IP,返回比较慢,可能返回失败;

  NSError *error;  
  NSURL *ipURL = [NSURL URLWithString:@"http://ifconfig.me/ip"];  
  NSString *ip = [NSString stringWithContentsOfURL:ipURL encoding:NSUTF8StringEncoding error:&error];
上一篇下一篇

猜你喜欢

热点阅读