获取相关IP所有信息

#include  

#include 

#include 

#define IOS_CELLULAR    @"pdp_ip0"  // 4G网路状态IP

#define IOS_WIFI        @"en0" // WIFI网路状态IP

//#define IOS_VPN      @"utun0" // VPN网路状态IP

#define IP_ADDR_IPv4    @"ipv4"

#define IP_ADDR_IPv6    @"ipv6"


//获取所有相关IP信息

- (NSDictionary *)getIPAddresses

{

    NSMutableDictionary *addresses = [NSMutableDictionary dictionaryWithCapacity:8];


    // retrieve the current interfaces - returns 0 on success

    structifaddrs*interfaces;

    if(!getifaddrs(&interfaces)) {

        // Loop through linked list of interfaces

        structifaddrs*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

            }

            conststructsockaddr_in*addr = (conststructsockaddr_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;

                        NSLog(@"对方PORT:%d ", ntohs(&addr->sin_port));

                    }

                }else{

                    conststructsockaddr_in6*addr6 = (conststructsockaddr_in6*)interface->ifa_addr;

                    if(inet_ntop(AF_INET6, &addr6->sin6_addr, addrBuf,INET6_ADDRSTRLEN)) {

                        type =IP_ADDR_IPv6;

                        NSLog(@"对方PORT:%d ", ntohs(&addr6->sin6_port));

                    }

                }

                if(type) {

                    NSString*key = [NSStringstringWithFormat:@"%@/%@", name, type];

                    addresses[key] = [NSStringstringWithUTF8String:addrBuf];

                }

            }

        }

        // Free memory

        freeifaddrs(interfaces);

    }

    return[addressescount] ? addresses :nil;

}

你可能感兴趣的:(获取相关IP所有信息)