How to check VPN connection status on Android ICS

江枫思渺然 提交于 2019-12-03 02:55:43
Victor Ronin

May be you can try to poll for DNS server changes. If it has changed then VPN has connected. However, I think there could be a lot of exception to this rule.

How do you get the current DNS servers for Android?

My solution is polling a NIC list.
# You can get the list by executing command "ls /sys/class/net".

If the list has "tun0", the device already has connected to VPN.

NetworkCapabilities worked for me in API 21+. Unfortunately I haven't found a solution for 19-20. You have to loop over all existing networks and check which has VPN_TRANSPORT

ConnectivityManager cm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
Network[] networks = cm.getAllNetworks();

Log.i(TAG, "Network count: " + networks.length);
for(int i = 0; i < networks.length; i++) {

  NetworkCapabilities caps = cm.getNetworkCapabilities(networks[i]);

  Log.i(TAG, "Network " + i + ": " + networks[i].toString());
  Log.i(TAG, "VPN transport is: " + caps.hasTransport(NetworkCapabilities.TRANSPORT_VPN));
  Log.i(TAG, "NOT_VPN capability is: " + caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN));

}
for (Enumeration<NetworkInterface> en =
             NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
            NetworkInterface intf = en.nextElement();
            if (intf.getName().contains("tun0") || intf.getName().contains("ppp0")) {
                vpnInterface = intf;
                break;
            }
        }

For the VPNNetwork Interface

for (Enumeration<InetAddress> en =
                 vpnInterface.getInetAddresses(); en.hasMoreElements(); ) {
                InetAddress address = en.nextElement();
                if (!address.isLoopbackAddress()) {
                    String ip = address.getHostAddress();
                    break;
                }
            }

and the InetAddress

Thats everything I know by the moment now

To check if it's up etc. maybe

if (vpnInterface.isUp())

I do have implemented a code which calls itself after a serveral time and send a message to the ApplicationHandlers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!