title: How to obtain the actual packet size `byte[]` array in Java UDP
body: <p>This is the subsequent question of my previous one:
  <a href="https://stackoverflow.com/questions/21866382/java-udp-send-receive-packet-one-by-one">Java UDP send - receive packet one by one</a></p>
  
  <p>As I indicated there, basically, I want to receive a packet one by one as it is via UDP.</p>
  
  <p>Here's an example code:</p>
  
  <pre><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");
  </code></pre>
  
  <p>Here, the actual packet size is say, 300bytes, but the <code>buffer1</code> is allocated as 1024 byte, and to me, it's something wrong with to deal with <code>buffer1</code>.</p>
  
  <p>How to obtain the actual packet size <code>byte[]</code> array from here?</p>
  
  <p>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 )</p>
  
  <p>Is there any way not to pre-allocate the buffer size and directly receive the UDP packet as it is?</p>
  
  <p>Thanks for your thought.</p>