美文网首页
获取内网,公网ip

获取内网,公网ip

作者: 廖丹_18be | 来源:发表于2017-08-03 11:38 被阅读159次

网上大量的文章都采用下面的方法,但只能获取到内网IP

#import <ifaddrs.h>
#import <arpa/inet.h>
#import <net/if.h>

#define IOS_CELLULAR    @"pdp_ip0"
#define IOS_WIFI        @"en0"
#define IOS_VPN         @"utun0"
#define IP_ADDR_IPv4    @"ipv4"
#define IP_ADDR_IPv6    @"ipv6"


#pragma mark - 获取设备当前网络IP地址
+ (NSString *)getIPAddress:(BOOL)preferIPv4
{
    NSArray *searchArray = preferIPv4 ?
    @[ 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 ] :
    @[ 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 ] ;

    NSDictionary *addresses = [self getIPAddresses];
    NSLog(@"addresses: %@", addresses);

    __block NSString *address;
    [searchArray enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop)
     {
         address = addresses[key];
         //筛选出IP地址格式
         if([self isValidatIP:address]) *stop = YES;
     } ];
    return address ? address : @"0.0.0.0";
}

想要获取公网ip,可以采用下面的方法:
方法1:

NSError*error;
NSURL*ipURL = [NSURL URLWithString:@"http://ifconfig.me/ip"];
NSString*ip = [NSString stringWithContentsOfURL:ipURL encoding:NSUTF8StringEncodingerror:&error];

方法2:(个人推荐用这个请求,速度比较快)

NSError*error;
NSURL*ipURL = [NSURL URLWithString:@"http://ipof.in/txt"];
NSString*ip = [NSString stringWithContentsOfURL:ipURL encoding:NSUTF8StringEncodingerror:&error];

相关文章

网友评论

      本文标题:获取内网,公网ip

      本文链接:https://www.haomeiwen.com/subject/mjtplxtx.html