3

In my Java app I receive DatagramPacket(s) through DatagramSocket. I know the maximum number of bytes which packet could contain, but actually every packet length varies (not exceeding max length).

Let's assume that MAX_PACKET_LENGTH = 1024 (bytes). So every time DatagramPacket is received it is 1024 bytes long, but not always all bytes contains information. It may happen that packet has 10 bytes of useful data, and the rest of 1014 bytes is filled with 0x00.

I am wondering if there is any elegant way to trim this 0x00 (unused) bytes in order to pass to the other layer only useful data? (maybe some java native methods? going in a loop and analysing what packet contains is not desired solution :))

Thanks for all hints. Piotr

omnomnom
  • 8,911
  • 4
  • 41
  • 50

2 Answers2

1

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

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226
  • I afraid that it doesn't return the actual length of the packet. Following code: int LENGTH = 887; DatagramPacket p = new DatagramPacket(new byte[LENGTH], LENGTH); System.out.println(p.getLength()); will print out 887 – omnomnom Jan 22 '11 at 18:38
  • 1
    It prints out 887 because 887 is the length of the packet (the 3rd arg to the constructor). This may be less than the size of the buffer (the first `LENGTH` in your example), but in your case it isn't – Chris Dodd Jan 24 '11 at 22:22
0

This is too late for the question but, could be useful for 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();
    }
}