Closed txchen closed 6 years ago
You need to handle the packet data for the duration of your packet event handler. If you need to copy any of the raw bytes, you need to do so before your event handler finishes, otherwise when the next packet arrives the previous data will be overwritten in the buffer.
buffer.slice()
returns a new Buffer
that references the same memory as the original buffer
, so that will not actually copy the bytes. An easy way to create an actual copy is to use Buffer.from(buffer)
(for the entire packet) or Buffer.from(buffer.slice(...))
for just whatever portion you want (you could also manually create a Buffer
and call buffer.copy(newBuffer, ...)
).
@mscdex Thanks for your quick answer!
So, is it possible that during copying the data to a new buffer, the original buffer got overwritten by a new packet? Or, can I assume it is safe before my event handler is done because nodejs will block the libpcap copy?
The buffer will not change for the duration of a 'packet'
event.
Thanks!
Maybe a dump question here:
In the usage example in README:
open takes only one buffer. And when it emits the event, only nbytes and trunc are returned in the event. The data is in the buffer.
Question: when I read the buffer and do some processing, will the next incoming packet write the buffer so that maybe I will read the wrong data? And what's the best practice to read the buffer, shall I always slice the buffer with nbytes?
Thanks a lot!