Android 无法写入 VPN 服务字节缓冲区

Android VPN service Bytebuffer can't be written

我正在开发一个带有 VPN 服务的数据包嗅探器 Android 应用程序,但是我在将数据包从 Fileinputstream 读取到字节缓冲区时遇到了问题。问题是每次我将数据包写入字节缓冲区时,字节缓冲区中都没有任何数据。请帮帮我。谢谢

 FileInputStream in = new FileInputStream(traffic_interface.getFileDescriptor());

                FileOutputStream out = new FileOutputStream(traffic_interface.getFileDescriptor());
                DatagramChannel tunnel = DatagramChannel.open();
                if (!protect(tunnel.socket())) {throw new IllegalStateException("Cannot protect the tunnel");}

                tunnel.connect((new InetSocketAddress("127.0.0.1",0)));
                tunnel.configureBlocking(false);
                int n = 0;

                while (!Thread.interrupted()){
                    packet = ByteBuffer.allocate(65535);

                    int packet_length = in.read(packet.array());
                    Log.d("UDPinStream","UDP:" +packet_length);

                    if(packet_length != -1 && packet_length > 0){
                        Log.d("UDPinStream","UDP:" + packet_length);
                        Log.d("UDPinStream","packet:" + packet);

                        packet.clear();
                    }

问题在下面的代码中

                int packet_length = in.read(packet.array());

                if(packet_length != -1 && packet_length > 0){
                    Log.d("UDPinStream","UDP:" + packet_length);
                    Log.d("UDPinStream","packet:" + packet);

                    packet.clear();
                }

虽然成功从隧道中读取数据包(packet_length>0),但Bytebuffer中也没有数据packetbytebuffer的pos没有改变。 java.nio.HeapByteBuffer[pos=0 lim=65535 cap=65535]

ByteBuffers 设计用于通道。您应该使用通道的任何 read/write(ByteBuffer buf) 接口来正确使用 ByteBuffers。

无论如何,在您的代码片段中,read() 获取 byte[],写入其中,但 ByteBuffer 不知道其支持的数组已填充。所以,你可以这样做,

if (packet_length != -1 && packet_length > 0) {
    packet.position(packet_length);  // filled till that pos
    packet.flip();                   // No more writes, make it ready for reading

   // Do read from packet buffer
   // then, packet.clear() or packet.compact() to read again.
}

在继续之前请看一下 NIO / ByteBuffer 示例。