Search code examples
iosunity-game-enginenetwork-programmingipipv6

Finding IPV6 address in Obj. C iphone


I am currently writing a unity plugin allowing me to use Game Center matchmaking with Mirror.

For this I need to find the IPV6 of the host to send it to the other player, however, I am unable to find an easy way to do this in obj C.

Before upgrading my code for IPV6 this is the code I used to get my IPV4:

+ (NSString *)GetInternalIpAddress
{
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    // Free memory
    freeifaddrs(interfaces);
    return address;
}

Any help would be greatly appreciated!!!


Solution

  • Here is what I ended up using:

    +(NSString *)GetIP
    {
        struct ifaddrs *ifa, *ifa_tmp;
        char addr[INET6_ADDRSTRLEN];
    
        if (getifaddrs(&ifa) == -1) {
            perror("getifaddrs failed");
            exit(1);
        }
    
        ifa_tmp = ifa;
        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));
                    if([[NSString stringWithUTF8String:ifa_tmp->ifa_name]  isEqual: @"en0"] && ![[NSString stringWithUTF8String:addr] containsString:@"::"])
                    {
                        printf("name = %s\n", ifa_tmp->ifa_name);
                        printf("addr = %s\n", addr);
    
                        return([NSString stringWithUTF8String:addr]);
                    }
                }
            }
            ifa_tmp = ifa_tmp->ifa_next;
        }
        freeifaddrs(ifa);
        return nil;
    }