How to obtain the actual packet size `byte[]` array in Java UDP

17,740

You've answered your own question. packet.getLength() returns the actual number of bytes in the received datagram. So, you just have to use buffer[] from index 0 to index packet.getLength()-1.

Note that this means that if you're calling receive() in a loop, you have to recreate the DatagramPacket each time around the loop, or reset its length to the maximum before the receive. Otherwise getLength() keeps shrinking to the size of the smallest datagram received so far.

Share:
17,740

Related videos on Youtube

Peter Burns
Author by

Peter Burns

Stack Overflow Valued Associate #00001 Wondering how our software development process works? Take a look! Find me on twitter, or read my blog. Don't say I didn't warn you because I totally did. However, I no longer work at Stack Exchange, Inc. I'll miss you all. Well, some of you, anyway. :)

Updated on June 21, 2022

Comments

  • Peter Burns
    Peter Burns almost 2 years

    This is the subsequent question of my previous one: Java UDP send - receive packet one by one

    As I indicated there, basically, I want to receive a packet one by one as it is via UDP.

    Here's an example code:

    ds = new DatagramSocket(localPort);
    byte[] buffer1 = new byte[1024];
    DatagramPacket packet = new DatagramPacket(buffer1, buffer1.length);
    
    ds.receive(packet); 
    Log.d("UDP-receiver",  packet.getLength() 
                                 + " bytes of the actual packet received");
    

    Here, the actual packet size is say, 300bytes, but the buffer1 is allocated as 1024 byte, and to me, it's something wrong with to deal with buffer1.

    How to obtain the actual packet size byte[] array from here?

    and, more fundamentally, why do we need to preallocate the buffer size to receive UDP packet in Java like this? ( node.js doesn't do this )

    Is there any way not to pre-allocate the buffer size and directly receive the UDP packet as it is?

    Thanks for your thought.

  • Admin
    Admin over 10 years
    Ok thanks EJP, I posted my own answer here. and it seems working properly looking at my log.