Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Sample Code to connect to VPN in Android 4.0 using VPNService API [closed]

Tags:

I am new to android and I am trying to establish and connect to our own vpn (Not the default vpn providers i.e, PPTP, 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?

like image 943
Sudarshan Avatar asked Nov 01 '12 12:11

Sudarshan


1 Answers

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:

https://github.com/hexene/LocalVPN

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 LocalVPNService.class
  • At LocalVPNService the TCP/UDP packet is investigated and source and destination IP's are extracted (Packet.class is used for that).
  • The LocalVPNService makes 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.

like image 170
hkoosha Avatar answered Sep 28 '22 06:09

hkoosha