Cropping 0x00 in resulting DatagramPacket

In my Java application, I get DatagramPacket (s) via DatagramSocket. I know the maximum number of bytes a packet can contain, but in fact each packet length changes (does not exceed the maximum length).

Suppose MAX_PACKET_LENGTH = 1024 (bytes). Therefore, every time a DatagramPacket is received, it has a length of 1024 bytes, but not all bytes always contain information. It may happen that a packet has 10 bytes of payload and the remaining 1014 bytes are filled with 0x00.

I am wondering if there is any elegant way to trim these 0x00 (unused) bytes in order to transfer only useful data to another layer? (maybe some Java built-in methods looping around and analyzing what the package contains are not a desirable solution :))

Thanks for all the tips. Peter

+3
source share
2 answers

You can call getLength on the DatagramPacket to return the ACTUAL packet length, which may be less than MAX_PACKET_LENGTH.

+1
source

This is too late for the question, but may be useful for a person like me.

   private int bufferSize = 1024;
/**
 * Sending the reply. 
 */
public void sendReply() {
    DatagramPacket qPacket = null;
    DatagramPacket reply = null;
    int port = 8002;
    try {
        // Send reply.
        if (qPacket != null) {
            byte[] tmpBuffer = new byte[bufferSize];
                            System.arraycopy(buffer, 0, tmpBuffer, 0, bufferSize);
            reply = new DatagramPacket(tmpBuffer, tmpBuffer.length,
                    qPacket.getAddress(), port);
            socket.send(reply);

        }

    }  catch (Exception e) {
        logger.error(" Could not able to recieve packet."
                + e.fillInStackTrace());

    }
}
/**
 * Receives the UDP ping request. 
 */
public void recievePacket() {
    DatagramPacket dPacket = null;
    byte[] buf = new byte[bufferSize];
    try {

        while (true) {
            dPacket = new DatagramPacket(buf, buf.length);
            socket.receive(dPacket);
            // This is a global variable.
            bufferSize = dPacket.getLength();

            sendReply();

        }

    } catch (Exception e) {
        logger.error(" Could not able to recieve packet." + e.fillInStackTrace());
    } finally {
        if (socket != null)
            socket.close();
    }
}
0
source

Source: https://habr.com/ru/post/1787170/


All Articles