简体   繁体   中英

Length of the UDP packets are written incorrectly

I wrote small program that is receives UDP packets and persists their data into a file.

        MulticastSocket socket = getMulticastSocket(interfaceAddress, multicastAddress, port);
        FileOutputStream fos = null;
        try{
            fos = new FileOutputStream(fileName);
            while(true) {
                byte[] data = new byte[BUFFER_SIZE];
                byte[] lengthBytes = new byte[4];
                DatagramPacket packet = new DatagramPacket(data, 0, data.length);
                socket.receive(packet);
                int length = packet.getLength();
                ByteBuffer lengthBB = ByteBuffer.wrap(lengthBytes);
                lengthBB.putInt(length);
                fos.write(lengthBB.array());
                fos.flush();
                fos.write(data, 0, length);
                fos.flush();
            }
        }

after that I am trying to read it use following code

final FileInputStream inputStream = new FileInputStream(fileName);
byte[] length = new byte[4];
while (inputStream.read(length) != -1){
    int receivedLength = ByteBuffer.wrap(length).getInt();
    byte[] body = new byte[receivedLength];
    inputStream.read(body);
    // doing something with body
    length = new byte[4];
}

it works in general but in the middle of file I have got negative value in receivedLength variable (-2147483648 and [-128, 0, 0, 0] in byte representation).

BUFFER_SIZE = 10240 but I do not think that package was greater than this value.

Question: why did it happen?

ps I do not have an access to machine where the file was written and I cannot look at the network stream. I have only the file.

The maximum size of a UDP message is 64K. You said that you don't think the packet was bigger than 10240 but it could be. Try increasing your buffer to 64 * 1024 and see if that changes the results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM