Andy
Andy

Reputation: 407

iOS Objective-C get VPN IP programmatically

I use a third-party app to connect a VPN, and we can get the detail information in Settings->VPN->information. How can I get the Assigned IP programmatically in our app by Objective-C?


enter image description here

Upvotes: 2

Views: 1493

Answers (2)

Foti Dim
Foti Dim

Reputation: 1371

This is working on iOS 14:

- (NSString *)getVPNIPAddress
{
    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)
            {
                NSLog(@"%@",[NSString stringWithUTF8String:temp_addr->ifa_name]);
                // Check if interface is en0 which is the wifi connection on the iPhone
                if(
                   [[NSString stringWithUTF8String:temp_addr->ifa_name] containsString:@"tun"] ||
                   [[NSString stringWithUTF8String:temp_addr->ifa_name] containsString:@"tap"] ||
                   [[NSString stringWithUTF8String:temp_addr->ifa_name] containsString:@"ipsec"] ||
                   [[NSString stringWithUTF8String:temp_addr->ifa_name] containsString:@"ppp"]){
                    // Get NSString from C String
                    struct sockaddr_in *in = (struct sockaddr_in*) temp_addr->ifa_addr;
                    address = [NSString stringWithUTF8String:inet_ntoa((in)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }

    // Free memory
    freeifaddrs(interfaces);
    return address;
}

Upvotes: 0

Will
Will

Reputation: 1696

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:@"utun1"])
            {
                // Get NSString from C String
                address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                NSLog(@"ifaName: %@, Address: %@",[NSString stringWithUTF8String:temp_addr->ifa_name],address);
            }
        }

        temp_addr = temp_addr->ifa_next;
    }
}

// Free memory
freeifaddrs(interfaces);

address will have the assigned IP Address

Upvotes: 1

Related Questions