• iOS获取设备IP地址


    项目用到要获取iOS设备的IP地址,有2种方法:

    1)第一种比较简单,但是只有当你的设备连接到WIFI时才能获取到IP地址,倘若你的设备用的是流量,那就不行。代码如下:

     1 #import <ifaddrs.h>  
     2 #import <arpa/inet.h>  
     3   
     4   
     5   
     6 // Get IP Address  
     7 - (NSString *)getIPAddress {      
     8     NSString *address = @"error";  
     9     struct ifaddrs *interfaces = NULL;  
    10     struct ifaddrs *temp_addr = NULL;  
    11     int success = 0;  
    12     // retrieve the current interfaces - returns 0 on success  
    13     success = getifaddrs(&interfaces);  
    14     if (success == 0) {  
    15         // Loop through linked list of interfaces  
    16         temp_addr = interfaces;  
    17         while(temp_addr != NULL) {  
    18             if(temp_addr->ifa_addr->sa_family == AF_INET) {  
    19                 // Check if interface is en0 which is the wifi connection on the iPhone  
    20                 if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {  
    21                     // Get NSString from C String  
    22                     address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];                 
    23                 }  
    24             }  
    25             temp_addr = temp_addr->ifa_next;  
    26         }  
    27     }  
    28     // Free memory  
    29     freeifaddrs(interfaces);  
    30     return address;  
    31   
    32 }   


    2)第二种方法比较通用,无论是WIFI还是流量都能获取到IP地址,代码如下:

     1 #import <ifaddrs.h>  
     2 #import <arpa/inet.h>  
     3 #import <net/if.h>  
     4   
     5 #define IOS_CELLULAR    @"pdp_ip0"  
     6 #define IOS_WIFI        @"en0"  
     7 #define IOS_VPN         @"utun0"  
     8 #define IP_ADDR_IPv4    @"ipv4"  
     9 #define IP_ADDR_IPv6    @"ipv6"  
    10   
    11   
    12 #pragma mark - 获取设备当前网络IP地址  
    13 + (NSString *)getIPAddress:(BOOL)preferIPv4  
    14 {  
    15     NSArray *searchArray = preferIPv4 ?  
    16     @[ IOS_VPN @"/" IP_ADDR_IPv4, IOS_VPN @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6 ] :  
    17     @[ IOS_VPN @"/" IP_ADDR_IPv6, IOS_VPN @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4 ] ;  
    18       
    19     NSDictionary *addresses = [self getIPAddresses];  
    20     NSLog(@"addresses: %@", addresses);  
    21       
    22     __block NSString *address;  
    23     [searchArray enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOLBOOL *stop)  
    24      {  
    25          address = addresses[key];  
    26          //筛选出IP地址格式  
    27          if([self isValidatIP:address]) *stop = YES;  
    28      } ];  
    29     return address ? address : @"0.0.0.0";  
    30 }  
    31   
    32 + (BOOL)isValidatIP:(NSString *)ipAddress {  
    33     if (ipAddress.length == 0) {  
    34         return NO;  
    35     }  
    36     NSString *urlRegEx = @"^([01]?\d\d?|2[0-4]\d|25[0-5])\."  
    37     "([01]?\d\d?|2[0-4]\d|25[0-5])\."  
    38     "([01]?\d\d?|2[0-4]\d|25[0-5])\."  
    39     "([01]?\d\d?|2[0-4]\d|25[0-5])$";  
    40       
    41     NSError *error;  
    42     NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:urlRegEx options:0 error:&error];  
    43       
    44     if (regex != nil) {  
    45         NSTextCheckingResult *firstMatch=[regex firstMatchInString:ipAddress options:0 range:NSMakeRange(0, [ipAddress length])];  
    46           
    47         if (firstMatch) {  
    48             NSRange resultRange = [firstMatch rangeAtIndex:0];  
    49             NSString *result=[ipAddress substringWithRange:resultRange];  
    50             //输出结果  
    51             NSLog(@"%@",result);  
    52             return YES;  
    53         }  
    54     }  
    55     return NO;  
    56 }  
    57   
    58 + (NSDictionary *)getIPAddresses  
    59 {  
    60     NSMutableDictionary *addresses = [NSMutableDictionary dictionaryWithCapacity:8];  
    61       
    62     // retrieve the current interfaces - returns 0 on success  
    63     struct ifaddrs *interfaces;  
    64     if(!getifaddrs(&interfaces)) {  
    65         // Loop through linked list of interfaces  
    66         struct ifaddrs *interface;  
    67         for(interface=interfaces; interface; interface=interface->ifa_next) {  
    68             if(!(interface->ifa_flags & IFF_UP) /* || (interface->ifa_flags & IFF_LOOPBACK) */ ) {  
    69                 continue; // deeply nested code harder to read  
    70             }  
    71             const struct sockaddr_in *addr = (const struct sockaddr_in*)interface->ifa_addr;  
    72             char addrBuf[ MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) ];  
    73             if(addr && (addr->sin_family==AF_INET || addr->sin_family==AF_INET6)) {  
    74                 NSString *name = [NSString stringWithUTF8String:interface->ifa_name];  
    75                 NSString *type;  
    76                 if(addr->sin_family == AF_INET) {  
    77                     if(inet_ntop(AF_INET, &addr->sin_addr, addrBuf, INET_ADDRSTRLEN)) {  
    78                         type = IP_ADDR_IPv4;  
    79                     }  
    80                 } else {  
    81                     const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6*)interface->ifa_addr;  
    82                     if(inet_ntop(AF_INET6, &addr6->sin6_addr, addrBuf, INET6_ADDRSTRLEN)) {  
    83                         type = IP_ADDR_IPv6;  
    84                     }  
    85                 }  
    86                 if(type) {  
    87                     NSString *key = [NSString stringWithFormat:@"%@/%@", name, type];  
    88                     addresses[key] = [NSString stringWithUTF8String:addrBuf];  
    89                 }  
    90             }  
    91         }  
    92         // Free memory  
    93         freeifaddrs(interfaces);  
    94     }  
    95     return [addresses count] ? addresses : nil;  
    96 }  


    Reference

    [1] http://superdanny.link/2016/01/27/iOS-get-device-ip-address/index.html

    [2] http://stackoverflow.com/questions/7072989/iphone-ipad-osx-how-to-get-my-ip-address-programmatically

    原文地址:http://blog.csdn.net/luoshengkim/article/details/51135063

  • 相关阅读:
    golang image库的使用
    http1.0/1.1/2.0/h2c/golang使用随笔
    3、逻辑回归 && 正则化
    1、Batch Normalization
    5、极大似然估计
    4、交叉熵与softmax
    2、卷积核,感受野
    Vue学习
    Qeios、github、overleaf、paperwithcode, 越来越多的web云端工具
    投稿遇到的arxiv论文引用问题的办法
  • 原文地址:https://www.cnblogs.com/SUPER-F/p/7298577.html
Copyright © 2020-2023  润新知