I am new to android and I am trying to establish and connect to our own
vpn (Not the default
vpn providers i.e,
L2TP etc which is present in the Android
Setting -> Wireless and Networks) programatically.
My scenario is, I have button and when I click the button I need to configure my own
vpn and a link (say www.google.com) should go through that
VPN which I had configured.
Is there any sample code?
I don’t know why I googled thousand times, but did not github’s search. Looking for ages now, I finally found one written beautifully. The code is literally beautiful which is rare:
The project does not use NDK or any native code, purely java, which makes it a perfect start for a simple project (not that it wont be good for a complex one). And the workflow is quite simple:
- When an app makes an outbound request (request from android OS to some server on internet) the request arrives
LocalVPNServicethe TCP/UDP packet is investigated and source and destination IP’s are extracted (
Packet.classis used for that).
LocalVPNServicemakes a connection on behalf of the app starting the request, and calls
VpnService.protect()on newly created connection to avoid loops.
- The connections are then passed to handlers who simply pass bytes from / to the two connection in a loop. The threads for UDP/TCP In/Out are managed in different worker classes and threads.
As you can see hexene has done all the hard work and heavy lifting already.
All the classes referenced above are found in the projects directory.
I had a quick look into the source code from github, the workflow discussed here might not be accurate.
You can refer the sample application ToyVpn which is bundled with your android SDK. so just go to samples and refer that application.Also see this
In additional to this you can download the source code of Openvpn. Here is the link to for that