Skip to content

Create a simple VPN Client for Android

trudyhood edited this page Dec 28, 2020 · 1 revision

You can establish a VpnHood client connection with a few line of code. For more information check samples.

Please note it is a simplest VpnHood client connection. If you are going to build a VPN application you can use or other NuGet packages. for more information Check VpnHood NuGet Packages.

First install the following NuGet packages.

PM> Install-Package VpnHood.Client
PM> Install-Package VpnHood.Client.Device.Android
private async Task ConnectTask()
{
    try
    {
        // disconnect if already connected
        if (IsConnectingOrConnected)
            Disconnect();

        // Connect
        // accessKey must obtain from the server
        var accessKey = "Your access code";
        var token = Token.FromAccessKey(accessKey);
        var clientId = Guid.Parse("7BD6C156-EEA3-43D5-90AF-B118FE47ED0B");
        var packetCapture = await Device.CreatePacketCapture();

        VpnHoodClient = new VpnHoodClient(packetCapture, clientId, token, new ClientOptions());
        VpnHoodClient.OnStateChanged += (object sender, EventArgs e) => UpdateUI();
        await VpnHoodClient.Connect();
    }
    catch (Exception ex)
    {
        var str = ex.Message;
    }
}

private void Disconnect()
{
    VpnHoodClient?.Dispose();
    VpnHoodClient = null;
}

private bool IsConnectingOrConnected => 
    VpnHoodClient?.State == ClientState.Connecting || VpnHoodClient?.State == ClientState.Connected;