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:
When the user presses the button to connect, call prepare(Context) and launch the returned intent, if non-null.
When the application becomes prepared, start the service.
Create a tunnel to the remote server and negotiate the network parameters for the VPN connection.
Supply those parameters to a VpnService.Builder and create a VPN interface by calling VpnService.Builder.establish().
Process and exchange packets between the tunnel and the returned file descriptor.
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>