How to exclude a website from VPN tun0 interface in Android

119 Views Asked by At

I have a VPN established where I do split tunneling with "builder.addallowedapplication()". I would like bypass a few websites from VPN tun0 and rather use the wlan0 interface.

I have tried using the following but doesn't seem to work. Please suggest any corrections.

    InetAddress[] inetAddresses = InetAddress.getAllByName("www.speedtest.net");
    for (InetAddress ipAddress : inetAddresses) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            String address = ipAddress.getHostAddress();
            builder.excludeRoute(new IpPrefix(InetAddress.getByName(address), 32));
        }
    }
1

There are 1 best solutions below

0
waheed708 On

Your code is good but make sure that you have configured the server to support split tunneling and try this code:

import android.os.Build;
import androidx.annotation.RequiresApi;
import android.net.IpPrefix;
import java.net.InetAddress;
import java.net.UnknownHostException;

@RequiresApi(api = Build.VERSION_CODES.Q)
public void excludeWebsitesFromVPN() {
    VpnService.Builder builder = new VpnService.Builder();
    
    try {
        InetAddress[] inetAddresses = InetAddress.getAllByName("www.speedtest.net");
        for (InetAddress ipAddress : inetAddresses) {
            String address = ipAddress.getHostAddress();
            builder.excludeRoute(new IpPrefix(ipAddress, 32));
        }
        vpnService = builder.setSession("myvpn").establish();
        vpnService.start();

    } catch (UnknownHostException e) {
        // Handle the exception if DNS lookup fails.
    }
}