Android VPN服务Bytebuffer无法编写

时间:2017-12-31 11:24:33

标签: java android fileinputstream bytebuffer

我正在使用VPN服务开发一个数据包嗅探器Android应用程序,但我在从Fileinputstream读取数据包到bytebuffer时遇到了麻烦。问题是每次我将数据包写入bytebuffer时,它都没有在bytebuffer中有任何数据。请帮帮我。感谢

 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),但字节缓冲区的pos中没有数据也没有变化。字节缓冲区的位置没有变化。 java.nio.HeapByteBuffer [pos = 0 lim = 65535 cap = 65535]

1 个答案:

答案 0 :(得分:0)

ByteBuffers旨在与频道协同工作。您应该使用通道的任何读/写(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示例。