Skip to content

gh-160622: Fix socket recv() and recvfrom() with MSG_TRUNC - #160677

Open
ViderStar wants to merge 1 commit into
python:mainfrom
ViderStar:gh-160622-recv-msg-trunc
Open

ViderStar wants to merge 1 commit into
python:mainfrom
ViderStar:gh-160622-recv-msg-trunc

Conversation

@ViderStar

@ViderStar ViderStar commented Oct 25, 2026 •

Copy link
Copy Markdown

With MSG_TRUNC, Linux recv(2)/recvfrom(2) return the real length of the datagram, which can be larger than the buffer. Since gh-157226, PyBytesWriter_FinishWithSize() rejects a size larger than the allocated one, so sock.recv(n, MSG_TRUNC) and sock.recvfrom(n, MSG_TRUNC) raise ValueError after the datagram has already been consumed.

This clamps the returned length to the requested size, so only the bytes actually received are returned (as suggested in gh-69121). recv_into() and recvfrom_into() are unchanged: they still return the value from the system call as is, which is the way to get the full datagram length.

Tests: added testRecvTrunc and testRecvFromTrunc to BasicUDPTest. On a Linux debug build they fail on main with ValueError: size larger than allocated size and pass with this change; full test_socket passes on Linux and macOS.

With MSG_TRUNC, recv() and recvfrom() can return the real length of
the datagram, which may be larger than the requested size. Since
PyBytesWriter_FinishWithSize() now rejects a size larger than the
allocated one, this raised ValueError after the datagram had already
been consumed. Return only the bytes actually received instead.
@python-cla-bot

Copy link
Copy Markdown

The following commit authors need to sign the Contributor License Agreement:

CLA not signed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant