DatagramPacket - will getData always return the same buffer which is passed?
Asked Answered
T

1

19
byte [] r = new byte[4096];
DatagramPacket dpr = new DatagramPacket(r, r.length);
sock.receive(dpr);

After the receive, will dpr.getData() & r always be the same?

ex: Can I directly use the byte array r or do I need to call getData() to retrieve the buffer again?

Testing it, showed it to be the same, but is this always guaranteed?

Touber answered 1/6, 2016 at 5:19 Comment(0)
M
9
byte [] r = new byte[4096];
DatagramPacket dpr = new DatagramPacket(r, r.length);
sock.receive(r);

That should be sock.receive(dpr);

After the receive, will dpr.getData() & r always be the same?

Yes. r was supplied to the constructor as 'the buffer for holding the incoming datagram', and getData() 'returns the buffer used to receive or send data'.

i.e. can I directly use the byte array r or do I need to call getData() to retrieve the buffer again?

You can use the byte array, but why? Use getData() like everybody else, not forgetting to also use getOffset() and getLength(), rather than assuming the datagram filled the byte array: for example, System.out.println(new String(datagram.getData(), datagram.getOffset(), datagram.getLength()));

Materfamilias answered 14/9, 2016 at 12:47 Comment(2)
Why would getOffset ever be anything other than 0?Touber
In your case it will be 0, but there are other constructors where the byte array is passed together with an offset. In that case the offset given in the constructor will be used. You should call getOffset in order to protect your code against nasty surprises if someone changes the call to the constructor in the future.Roentgenology

© 2022 - 2024 — McMap. All rights reserved.