如何在iOS中区分ipv4和ipv6?

时间:2017-10-12 11:49:21

标签: ios sip ipv6 pjsip ipv4

我们计划使用IPv6更新基于pjsip的iOS SDK。我们开发了IPv6环境。如果设备IP属于IPv6别名IPv4(ipv4.url.com),我们计划调用IPv6服务器(ipv6.url.com)。那么从iOS SDK中有没有办法区分IPv4和IPv6?

1 个答案:

答案 0 :(得分:1)

首先添加以下标题,

#include <ifaddrs.h>

#include <sys/socket.h>

#include <arpa/inet.h>

- (BOOL)ifIPv6Address
{
    struct ifaddrs *ifa, *ifa_tmp;
    char addr[50];

    if (getifaddrs(&ifa) == -1) {
        perror("getifaddrs failed");
        exit(1);
    }

    ifa_tmp = ifa;
    BOOL ipv6Found = NO;

    while (ifa_tmp) {
        if ((ifa_tmp->ifa_addr) && ((ifa_tmp->ifa_addr->sa_family == AF_INET) ||
                                (ifa_tmp->ifa_addr->sa_family == AF_INET6))) 
    {
            if (ifa_tmp->ifa_addr->sa_family == AF_INET) {
                 // create IPv4 string
                 struct sockaddr_in *in = (struct sockaddr_in*) ifa_tmp->ifa_addr;
                 inet_ntop(AF_INET, &in->sin_addr, addr, sizeof(addr));
             } else { // AF_INET6
                 // create IPv6 string
                 struct sockaddr_in6 *in6 = (struct sockaddr_in6*) ifa_tmp->ifa_addr;
            inet_ntop(AF_INET6, &in6->sin6_addr, addr, sizeof(addr));
        }

        NSRange range = [[NSString stringWithFormat:@"%s",addr] rangeOfString:[NSString stringWithFormat:@":"]];
        if (range.location!=NSNotFound)
        {
            NSError *error = NULL;
            NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@":" options:NSRegularExpressionCaseInsensitive error:&error];
            NSUInteger numberOfMatches = [regex numberOfMatchesInString:[NSString stringWithFormat:@"%s",addr] options:0 range:NSMakeRange(0, [[NSString stringWithFormat:@"%s",addr] length])];
            NSLog(@"Found -> %lu",(unsigned long)numberOfMatches);
            if (numberOfMatches >= 7) {
                ipv6Found = YES;
                break;
            }
        }
        //            printf("name = %s\n", ifa_tmp->ifa_name);
        //            printf("addr = %s\n", addr);
        }
        ifa_tmp = ifa_tmp->ifa_next;
    }

    if (ipv6Found) {
        return YES;
    } else {
        return NO;
    }
}