title: How to trigger on-Demand VPN with Objective-C on iOS
body: <p>I have an iPad application which opens a socket connection to a server in Intranet using socket libraries in C . While starting the application, if the iPad is not connected to the same network (i.e. can not resolve the Domain Name of the server), I expect it to establish a VPN connection automatically. But socket calls and getaddrinfo() methods in the application can not do this. They just fail to connect to the server without trying to open the VPN connection. </p>
  
  <p>With Safari, browsing to the address "http://..." works fine and succesfully starts the VPN. If I make a similar HTTP request in the beginning of the application by using the code below, I can make it start the VPN connection. But sending an additional http request is the best solution for me. VPN should start whenever iPad needs to resolve the domain name, without any dependency for the protocol or remote port number.</p>
  
  <pre><code>NSString* urlForVPN = @"http://..";
  NSURLRequest * urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:urlForVPN] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0];
  [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&amp;response error:&amp;error];
  </code></pre>
  
  <p>On Apple developer site it says "Avoid Resolving DNS Names Before Connecting to a Host. The preferred way to connect to a host is with an API that accepts a DNS name, such as <strong>CFHost</strong> or <strong>CFNetService</strong>" (<a href="https://developer.apple.com/library/ios/documentation/NetworkingInternetWeb/Conceptual/NetworkingOverview/CommonPitfalls/CommonPitfalls.html" rel="nofollow">https://developer.apple.com/library/ios/documentation/NetworkingInternetWeb/Conceptual/NetworkingOverview/CommonPitfalls/CommonPitfalls.html</a>). Accordingly, I was hoping that the following code should start VPN while trying to resolve the server name, but it does not work either. It just fails to get the IP address. I had to manually switch on the VPN to make it connect to the server.</p>
  
  <pre><code>NSString* hostname = @"myserver";
  CFHostRef hostRef = CFHostCreateWithName(kCFAllocatorDefault, (CFStringRef)hostname);
  BOOL isSuccess = CFHostStartInfoResolution(hostRef, kCFHostAddresses, nil);
  </code></pre>
  
  <p>How can I make an application understand that it needs to start the VPN? 
  Does "VPN on-demand" work only for URL connections?</p>