[New-bugs-announce] [issue24169] sockets convert out-of-range port numbers % 2**16

Kurt Rose report at bugs.python.org
Tue May 12 20:50:58 CEST 2015

New submission from Kurt Rose:

This appears to affect all versions of Python.  In a behavior inherited from C, TCP ports that are > 2 bytes are silently truncated.

Here is a simple reproduction:

>>> socket.create_connection( ('google.com', 2**16 + 80) )
<socket.socket object, fd=408, family=2, type=1, proto=0>

Needs more investigation, but one likely place to make the fix is here:

        if (!PyArg_ParseTuple(args, "O&i:getsockaddrarg",
                              idna_converter, &host, &port))

Instead of parsing port with i, use H.  This is a deep change to the behavior, but I think it is very unlikely that users intentionally mean to pass a TCP port > 2**16.  More likely, this is silently swallowing errors. 

There no indication that the passed port parameter is not being used for the actual TCP communication (which is physically impossible because TCP only has a 2 byte port field).

In fact, the socket will continue to "lie" to the user and obfuscate the actual port being used if getsockname() is called:

>>> socket.create_connection( ('google.com', 2**16 + 80) ).getsockname()
('', 54899)

messages: 242987
nosy: Kurt.Rose
priority: normal
severity: normal
status: open
title: sockets convert out-of-range port numbers % 2**16
type: behavior
versions: Python 2.7, Python 3.2, Python 3.3, Python 3.4, Python 3.5, Python 3.6

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list