我试图找出我的设备上的哪个应用程序已经发出任何互联网使用请求(称为任何api等).为此我创建了一个从"VpnService"类扩展的类,以确保我的设备流量通过我,虽然我实际上并没有连接到VPN,而是假装它让流量通过我到0.0.0.0.代码如下,它工作正常,但我想弄清楚哪个应用程序已启动使用互联网的请求或其数据包是在下面的主循环中进/出.另外,有没有办法可以阻止来自任何应用程序的请求 - 无论是[传入还是传出]?
*private Thread mThread;
private ParcelFileDescriptor mInterface;
//a. Configure a builder for the interface.
Builder builder = new Builder();
// Services interface
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
this.getApplicationInfo();
// Start a new session by creating a new thread.
mThread = new Thread(new Runnable() {
@Override
public void run() {
try {
//a. Configure the TUN and get the interface.
mInterface = builder.setSession("MyVPNService")
.setMtu(1500)
.addAddress("192.168.1.66", 32)
.addRoute("0.0.0.0", 0).establish();
//b. Packets to be sent are queued in this input stream.
FileInputStream in = new FileInputStream(
mInterface.getFileDescriptor());
//b. Packets received need to be written to this output stream.
FileOutputStream out = new FileOutputStream(
mInterface.getFileDescriptor());
//c. The UDP channel can be used to pass/get ip package to/from server
DatagramChannel tunnel = DatagramChannel.open();
// Connect to the server, localhost is used for demonstration only.
tunnel.connect(new InetSocketAddress("127.0.0.1", 8087));
//d. Protect this socket, so package send by it will not be feedback to the vpn service.
protect(tunnel.socket());
// ByteBuffer packet = ByteBuffer.allocate(32767);
//e. Use a loop to pass packets.
while (true) {
//---> Here in this loop the packets are coming in and out..
}
}
} catch (Exception e) {
// Catch any exception
e.printStackTrace();
} finally {
try {
if (mInterface != null) {
mInterface.close();
mInterface = null;
}
} catch (Exception e) {
}
}
}
}, "MyVpnRunnable");
//start the service
mThread.start();
return START_STICKY;
}*
Run Code Online (Sandbox Code Playgroud)
里诺琼斯
恐怕仅靠 VpnService 的帮助无法做到这一点。您无法使用普通的 VpnService API 获取必要的信息。
然而,这对于 iptables(当然还有 root 的手机......)来说是微不足道的,如下所示:
iptables -t mangle -A PREROUTING -m owner --uid-owner bad_app_uid -j DROP
你需要
我不知道如何阻止每个应用程序的传入流量 - 但似乎不是很有必要。
如果你确实想尝试一下,https://github.com/shadowsocks/shadowsocks-android会编译 iptables,我想它也可能适合你。顺便说一句,我与提到的应用程序无关。
编辑:Android 5.0 VpnService 有几个新的 API,例如addAllowedApplication和addDisallowedApplication,但这里的“禁止”仅意味着指定的应用程序将绕过 VPN。