iOS -- 获取当前设备的IP地址

iOS – 获取当前设备的IP地址

导入依赖库

获取iOS设备地址需要以下两个文件

#import 
#import 

获取地址结构体对象,并遍历

+ (NSString *)getNetworkAddressDetailHandler:(void(^)(NSString *interface, NSString *address, NSString *addressType))handler
{
    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) {
            [self getAddress:temp_addr handler:handler];
            temp_addr = temp_addr->ifa_next;
        }
    }
    freeifaddrs(interfaces);
    return nil;
}

处理单个地址对象


+ (void)getAddress:(struct ifaddrs *)temp_addr handler:(void(^)(NSString *interface, NSString *address, NSString *addressType))handler
{
    // 网络地址族
    sa_family_t sa_family = temp_addr->ifa_addr->sa_family;
    // 网络接口
    NSString *interface;
    // 网络地址
    NSString *address;
    // 网络地址
    NSString *addressType;
    // IPv4
    if(sa_family == AF_INET){
        interface = [NSString stringWithUTF8String:temp_addr->ifa_name];
        struct sockaddr_in *ifa_addr = ((struct sockaddr_in *)temp_addr->ifa_addr);
        address = [NSString stringWithUTF8String:inet_ntoa(ifa_addr->sin_addr)];
        addressType = @"IPv4";
    }
    // IPv6
    else if (sa_family == AF_INET6){
        interface = [NSString stringWithUTF8String:temp_addr->ifa_name];
        struct sockaddr_in6 *ifa_addr = ((struct sockaddr_in6 *)temp_addr->ifa_addr);
        char buf[INET6_ADDRSTRLEN] = {0};
        const char *ipv6 = inet_ntop(AF_INET6, &ifa_addr->sin6_addr, buf, sizeof(buf));
        address = [NSString stringWithUTF8String:ipv6];
        addressType = @"IPv6";
    }
    if (interface.length && handler){
        handler(interface, address, addressType);
    }
}

地址类型释义

temp_addr->ifa_name

/**
 lo     本地回环 (Loopback)
 en     无线网 (WiFi)
 pdp_ip 蜂窝网络 (Cellular)
 awdl   通信Wi-Fi (Apple Wireless Direct Link,用于AirDrop、AirPlay、GameKit 和 Apple Pencil )
 utun   虚拟隧道 (VPN)
 ipsec  虚拟隧道 (VPN)
 llw    低延迟无线局域网(Low-latency WLAN)
 */

Demo

Demo

截图

iOS -- 获取当前设备的IP地址_第1张图片

你可能感兴趣的:(iOS,ios,objective-c,IP地址)