1
votes

I am learning to program UDP a bit. How would I get the size of a packet I receive from a UDP server?

byte[] buffer = new byte[1000];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
datagramSocket.receive(packet);
buffer = packet.getData();

In the above code snippet, I am declaring the buffer size as 1000 bytes. So it is obvious that I cannot get the size by simply calling buffer.length which will return 1000 in any case.

Can someone please tell me if there is a way to do it?

1
Seriously dude, did you read the javadoc before asking this question? And if not, why not?Stephen C

1 Answers

3
votes

You could use the getLength() method in DatagramPacket, such as packet.getLength() to be able to get the packet size.