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.