2

I've been parsing the web for a way to create a VPN client on Android. I can't seem to find any good resources on how to do this.

The goal is , I would like to be able to setup a VPN using either the built in VPN feature in Android (perhaps programatically adding a new connection) or otherwise.

I did come across the VpnService in the docs but its unclear on how to use it. Does anyone have a good example of doing this and is this possible with the Android SDK as at this time?

fitzmode
  • 1,007
  • 1
  • 18
  • 29

1 Answers1

3

Android gives a sample code ToyVpn which you can look and reuse logic for your need.


And here is some details from documentation

There are two primary methods in this class: prepare(Context) and VpnService.Builder.establish(). The former deals with user action and stops the VPN connection created by another application. The latter creates a VPN interface using the parameters supplied to the VpnService.Builder. An application must call prepare(Context) to grant the right to use other methods in this class, and the right can be revoked at any time. Here are the general steps to create a VPN connection:

  1. When the user presses the button to connect, call prepare(Context) and launch the returned intent, if non-null.

  2. When the application becomes prepared, start the service.

  3. Create a tunnel to the remote server and negotiate the network parameters for the VPN connection.

  4. Supply those parameters to a VpnService.Builder and create a VPN interface by calling VpnService.Builder.establish().

  5. Process and exchange packets between the tunnel and the returned file descriptor.

  6. When onRevoke() is invoked, close the file descriptor and shut down the tunnel gracefully.

Services extending this class need to be declared with an appropriate permission and intent filter. Their access must be secured by Manifest.permission.BIND_VPN_SERVICE permission, and their intent filter must match SERVICE_INTERFACE action. Here is an example of declaring a VPN service in AndroidManifest.xml:

<service android:name=".ExampleVpnService"
         android:permission="android.permission.BIND_VPN_SERVICE">
     <intent-filter>
         <action android:name="android.net.VpnService"/>
     </intent-filter>
 </service>
Pankaj Kumar
  • 81,967
  • 29
  • 167
  • 186
  • Hi Pankaj! Is it possible to only change the dns address and leave the rest? I don’t really know what .addAddress or .addRoute does and I only really want to change the dns – Casanova Apr 23 '20 at 08:21