From 9b038ba321a884c6a1febd0c0995c802769b7dcf Mon Sep 17 00:00:00 2001 From: Florian Lehner Date: Tue, 25 Jun 2024 19:20:19 +0200 Subject: [PATCH] conn: reduce initial memory in Receive() Reduce memory footprint by starting with a smaller buffer and adjust the buffer size accordingly after peeking at the upcoming netlink message. Signed-off-by: Florian Lehner --- conn_linux.go | 30 +++++++++++------------------- 1 file changed, 11 insertions(+), 19 deletions(-) diff --git a/conn_linux.go b/conn_linux.go index 4af18c9..ed105b0 100644 --- a/conn_linux.go +++ b/conn_linux.go @@ -121,28 +121,20 @@ func (c *conn) Send(m Message) error { // Receive receives one or more Messages from netlink. func (c *conn) Receive() ([]Message, error) { - b := make([]byte, os.Getpagesize()) - for { - // Peek at the buffer to see how many bytes are available. - // - // TODO(mdlayher): deal with OOB message data if available, such as - // when PacketInfo ConnOption is true. - n, _, _, _, err := c.s.Recvmsg(context.Background(), b, nil, unix.MSG_PEEK) - if err != nil { - return nil, err - } - - // Break when we can read all messages - if n < len(b) { - break - } - - // Double in size if not enough bytes - b = make([]byte, len(b)*2) + b := make([]byte, unix.SizeofNlMsghdr) + // Peek at the buffer to see how many bytes are available. + // + // TODO(mdlayher): deal with OOB message data if available, such as + // when PacketInfo ConnOption is true. + n, _, _, _, err := c.s.Recvmsg(context.Background(), b, nil, unix.MSG_PEEK|unix.MSG_TRUNC) + if err != nil { + return nil, err } + // Resize buffer to the expected size. + b = make([]byte, nlmsgAlign(n)) // Read out all available messages - n, _, _, _, err := c.s.Recvmsg(context.Background(), b, nil, 0) + n, _, _, _, err = c.s.Recvmsg(context.Background(), b, nil, 0) if err != nil { return nil, err }