How to run an on-demand VPN request using Objective-C on iOS

I have an iPad application that opens a socket connection to a server in Intranet using socket libraries in C. When I start the application, if the iPad is not connected to the same network (i.e. Can’t resolve the server’s domain name), I expect that it will automatically establish a VPN connection. But socket calls and getaddrinfo () methods in an application cannot do this. They simply cannot connect to the server without trying to open a VPN connection.

With Safari, browsing to the address "http: // ..." works fine and successfully starts a VPN. If I make a similar HTTP request at the beginning of the application using the code below, I can start a VPN connection. But sending an extra HTTP request is the best solution for me. The VPN should start whenever the iPad needs to resolve the domain name without any dependency on the protocol or remote port number.

NSString* urlForVPN = @"http://..";
NSURLRequest * urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:urlForVPN] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0];
[NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];

The Apple Developer website says: “Avoid resolving DNS names before connecting to the host. The preferred way to connect to the host is an API that accepts a DNS name such as CFHost or CFNetService ” ( https://developer.apple.com/library /ios/documentation/NetworkingInternetWeb/Conceptual/NetworkingOverview/CommonPitfalls/CommonPitfalls.html ). Accordingly, I was hoping that the following code should start the VPN when trying to resolve the server name, but it also does not work. It just does not get the IP address. I had to manually turn on the VPN to connect to the server.

NSString* hostname = @"myserver";
CFHostRef hostRef = CFHostCreateWithName(kCFAllocatorDefault, (CFStringRef)hostname);
BOOL isSuccess = CFHostStartInfoResolution(hostRef, kCFHostAddresses, nil);

How can I make an application understand that it needs to start a VPN? VPN on Demand works only for URL connections?

+4

Source: https://habr.com/ru/post/1535389/


All Articles