开发锦集iOS Developer

获取ip地址:内网、外网、4G

2017-07-27  本文已影响155人  YvanLiu

一般的方法

- (NSString *)getIPAddress {
    NSString *address = @"0.0.0.0";
    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);
    return address;
}

这种方法拿到的ip地址,仅限于wifi情况下拿到内网ip,如果手机是处于4G或3G状态,拿不到ip。

比较牛逼的

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

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

//获取设备当前网络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];
         if(address) *stop = YES;
     } ];
    return address ? address : @"0.0.0.0";
}

//获取所有相关IP信息
+ (NSDictionary *)getIPAddresses
{
    NSMutableDictionary *addresses = [NSMutableDictionary dictionaryWithCapacity:8];
    
    // retrieve the current interfaces - returns 0 on success
    struct ifaddrs *interfaces;
    if(!getifaddrs(&interfaces)) {
        // Loop through linked list of interfaces
        struct ifaddrs *interface;
        for(interface=interfaces; interface; interface=interface->ifa_next) {
            if(!(interface->ifa_flags & IFF_UP) /* || (interface->ifa_flags & IFF_LOOPBACK) */ ) {
                continue; // deeply nested code harder to read
            }
            const struct sockaddr_in *addr = (const struct sockaddr_in*)interface->ifa_addr;
            char addrBuf[ MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) ];
            if(addr && (addr->sin_family==AF_INET || addr->sin_family==AF_INET6)) {
                NSString *name = [NSString stringWithUTF8String:interface->ifa_name];
                NSString *type;
                if(addr->sin_family == AF_INET) {
                    if(inet_ntop(AF_INET, &addr->sin_addr, addrBuf, INET_ADDRSTRLEN)) {
                        type = IP_ADDR_IPv4;
                    }
                } else {
                    const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6*)interface->ifa_addr;
                    if(inet_ntop(AF_INET6, &addr6->sin6_addr, addrBuf, INET6_ADDRSTRLEN)) {
                        type = IP_ADDR_IPv6;
                    }
                }
                if(type) {
                    NSString *key = [NSString stringWithFormat:@"%@/%@", name, type];
                    addresses[key] = [NSString stringWithUTF8String:addrBuf];
                }
            }
        }
        // Free memory
        freeifaddrs(interfaces);
    }
    return [addresses count] ? addresses : nil;
}

+ (NSString *)getIPAddress:(BOOL)preferIPv4;
/****************************
 函数描述:获取IP地址
 输入参数:是否Ipv4的IP
 输出参数:IP地址
 ****************************/

调用

[HDTools getIPAddress:YES];
// 这个是前面打的log
addresses: {
    "awdl0/ipv6" = "fe80::407e:9cff:fee6:4e54";
    "en0/ipv4" = "192.168.62.221";
    "en0/ipv6" = "fe80::489:9fdb:9112:697a";
    "en2/ipv4" = "169.254.113.103";
    "en2/ipv6" = "fe80::56:ec03:106c:ca90";
    "lo0/ipv4" = "127.0.0.1";
    "lo0/ipv6" = "fe80::1";
    "pdp_ip0/ipv4" = "10.169.87.31";
    "utun0/ipv6" = "fe80::56b2:b9c2:1e1f:42a";
}
// 这个是输出的结果
192.168.62.221

// lo0         //本地ip, 
// en0        //局域网ip, 
// pdp_ip0  //WWAN地址,即4G ip,
// bridge0  //桥接、热点ip,

这个方法是我亲手在网上找的~~~~
这个方法应该是我们比较实用的一种了,无论是wifi还是4G都能拿到ip地址,只不过这个也拿不到外网ip。

拿外网ip

在网上找到一个特别简单的方法:

NSError *error;
NSURL *ipURL = [NSURL URLWithString:@"http://pv.sohu.com/cityjson?ie=utf-8"];
NSString *ip = [NSString stringWithContentsOfURL:ipURL encoding:NSUTF8StringEncoding error:&error];
NSLog(@"%@",ip);

输出结果:

var returnCitySN = {"cip": "106.38.55.122", "cid": "CN", "cname": "CHINA"};

拿到的是这么个东西,然后我简单处理了一下。

    if ([ip rangeOfString:@"var returnCitySN = "].location != NSNotFound) {
        ip = [[ip componentsSeparatedByString:@"var returnCitySN = "] lastObject];
        ip = [[ip componentsSeparatedByString:@";"] firstObject];
        SBJsonParser* json =[[SBJsonParser alloc]init];
        NSDictionary* dic =[json objectWithString:ip];
        NSLog(@"%@",dic);
        ip = dic[@"cip"];
    } else {
        ip = @"0.0.0.0";
    }
    
    NSLog(@"%@",ip);

还有一个地址:http://ifconfig.me/ip
这个可以点进去看一下,拿到的直接就是外网ip不用做任何处理。同样用上面的方法。

<b><i>所有的方法都是在其他的地方找到的,亲测有用,整理一下贴出来以防以后用的时候找不到。</i></b>

友情提示:

<i>如果使用第三个方法拿外网ip的时候返回null,考虑一下是不是因为iOS10之后不能正常访问http的连接,需要去info.plist中设置一下。</i>

还有我用的是真机测试,没有测模拟器。

上一篇下一篇

猜你喜欢

热点阅读