【问题标题】:How to check VPN connection status on Android ICS如何在 Android ICS 上检查 VPN 连接状态
【发布时间】:2012-06-06 17:38:54
【问题描述】:
我正在尝试注册接收器,它将检查 VPN 状态。我试过这个:Get VPN Connection status on Android 但看起来它不再适用于 ICS。我检查了 android 源代码以获取一些线索,但没有运气,只注意到在 ISC 中没有类似:vpn.connectivity 和 connection_state - 它曾经在 android 2.3 中。还尝试使用android.net.conn.CONNECTIVITY_CHANGE 作为我的IntentFilter,但它根本不会对VPN 连接做出反应(当然我已经添加了权限android.permission.ACCESS_NETWORK_STATE)。
我认为这很简单,但我已经不知道该怎么做了……有人可以帮我解决这个问题吗?
【问题讨论】:
标签:
android
broadcastreceiver
vpn
【解决方案1】:
for (Enumeration<NetworkInterface> en =
NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
if (intf.getName().contains("tun0") || intf.getName().contains("ppp0")) {
vpnInterface = intf;
break;
}
}
对于 VPN 网络接口
for (Enumeration<InetAddress> en =
vpnInterface.getInetAddresses(); en.hasMoreElements(); ) {
InetAddress address = en.nextElement();
if (!address.isLoopbackAddress()) {
String ip = address.getHostAddress();
break;
}
}
和 InetAddress
这就是我现在所知道的一切
检查它是否启动等。也许
if (vpnInterface.isUp())
我确实实现了一段代码,它会在一段时间后调用自身并向 ApplicationHandlers 发送消息
【解决方案2】:
NetworkCapabilities 在 API 21+ 中为我工作。不幸的是,我还没有找到 19-20 的解决方案。您必须遍历所有现有网络并检查哪个有 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));
}
【解决方案3】:
我的解决方案是轮询 NIC 列表。
# 可以通过执行命令“ls /sys/class/net”获取列表。
如果列表中有“tun0”,则设备已经连接到 VPN。