Author Oren Milman
Recipients Oren Milman
Date 2016-10-01.15:05:54
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <>
------------ current state ------------
Due to the implementation of socket_htons (in Modules/socketmodule.c), in case the received integer does not fit in 16-bit unsigned integer, but does fit in a positive C int, it is silently truncated to 16-bit unsigned integer (before converting to network byte order):
>>> import socket
>>> hex(socket.htons(0x1234))
>>> hex(socket.htons(0x81234))
>>> hex(socket.htons(0x881234))
>>> hex(socket.htons(0x8881234))
>>> hex(socket.htons(0x88881234))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: Python int too large to convert to C long

Likewise, socket.ntohs has the same silent truncation feature, due to the implementation of socket_ntohs.

ISTM this silent truncation feature has the potential to conceal nasty bugs, and I guess it is rarely used in purpose.

With regard to relevant changes made in the past:
    * The silent truncation was there since the two functions were first added, in changeset 3673 (
    * A check whether the received integer is negative was added (to each of the two functions) in changeset 40632 (, as part of #1635058.
    Note the lack of discussion in #1635058 and #1619659 about backward compatibility. It might suggest that Guido didn't hesitate to make the change, even though at the time, the four conversion functions (socket.htons, socket.ntohs, socket.htonl and socket.ntohl) were already in the wild for 10 years.

------------ proposed changes ------------
    1. In Modules/socketmodule.c, raise a DeprecationWarning before silently truncating the received integer. In Python 3.8, replace the DeprecationWarning with an OverflowError.

    2. In Lib/test/, add tests to verify a DeprecationWarning is raised as expected.

    3. In Doc/library/socket.rst, add a description of the silent truncation feature, and declare it is deprecated.

------------ diff ------------
The proposed patches diff file is attached.

(I wasn't sure you would approve deprecating a feature that was in the wild for so long, but I implemented it anyway, as it was quite simple.)

------------ tests ------------
I ran 'python_d.exe -m test -j3' (on my 64-bit Windows 10) with and without the patches, and got quite the same output. (That also means my new tests in test_socket passed.)
The outputs of both runs are attached.
Date User Action Args
2016-10-01 15:06:10Oren Milmansetrecipients: + Oren Milman
2016-10-01 15:06:10Oren Milmansetmessageid: <>
2016-10-01 15:06:10Oren Milmanlinkissue28332 messages
2016-10-01 15:06:07Oren Milmancreate