Android用代码判断是否在使用VPN

原文地址:https://blog.csdn.net/gaojinshan/article/details/51678968

扫描所有网络接口,查看是否有使用VPN的(接口名为tun0或ppp0):

[java]  view plain  copy
  1. public static boolean isVpnUsed() {  
  2.     try {  
  3.         Enumeration<NetworkInterface> niList = NetworkInterface.getNetworkInterfaces();  
  4.         if(niList != null) {  
  5.             for (NetworkInterface intf : Collections.list(niList)) {  
  6.                 if(!intf.isUp() || intf.getInterfaceAddresses().size() == 0) {  
  7.                     continue;  
  8.                 }  
  9.                 Log.d(TAG, "isVpnUsed() NetworkInterface Name: " + intf.getName());  
  10.                 if ("tun0".equals(intf.getName()) || "ppp0".equals(intf.getName())){                          
  11.                     return true// The VPN is up  
  12.                 }  
  13.             }  
  14.         }  
  15.     } catch (Throwable e) {  
  16.         e.printStackTrace();  
  17.     }  
  18.     return false;  
  19. }  

比如,下面是所有网络接口的列表:

[plain]  view plain  copy
  1. c = {ArrayList@830054223664}  size = 10  
  2.  0 = {NetworkInterface@830057714392} "[p2p0][8][/fe80::7c7d:3dff:fe4d:ad0f%p2p0%8]"  
  3.  1 = {NetworkInterface@830057715208} "[sit0][2]"  
  4.  2 = {NetworkInterface@830054463232} "[tun0][30][/172.66.0.9]"   ////这个接口就是VPN  
  5.  3 = {NetworkInterface@830054320152} "[lo][1][/::1%1%1][/127.0.0.1]"  
  6.  4 = {NetworkInterface@830054286792} "[wlan0][9]"  
  7.  5 = {NetworkInterface@830054270304} "[rmnet0][3][/100.84.44.157]"  
  8.  6 = {NetworkInterface@830054259216} "[rmnet1][4]"  
  9.  7 = {NetworkInterface@830054246600} "[rmnet3][6]"  
  10.  8 = {NetworkInterface@830054236272} "[rmnet2][5]"  
  11.  9 = {NetworkInterface@830054224840} "[rmnet4][7]"  

猜你喜欢

转载自blog.csdn.net/dodod2012/article/details/80282912