MCPcopy Index your code
hub / github.com/python/cpython / bind_port

Function bind_port

Lib/test/support/socket_helper.py:81–118  ·  view source on GitHub ↗

Bind the socket to a free port and return the port number. Relies on ephemeral ports in order to ensure we are using an unbound port. This is important as many tests may be running simultaneously, especially in a buildbot environment. This method raises an exception if the sock.family

(sock, host=HOST)

Source from the content-addressed store, hash-verified

79 return port
80
81def bind_port(sock, host=HOST):
82 """Bind the socket to a free port and return the port number. Relies on
83 ephemeral ports in order to ensure we are using an unbound port. This is
84 important as many tests may be running simultaneously, especially in a
85 buildbot environment. This method raises an exception if the sock.family
86 is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR
87 or SO_REUSEPORT set on it. Tests should *never* set these socket options
88 for TCP/IP sockets. The only case for setting these options is testing
89 multicasting via multiple UDP sockets.
90
91 Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e.
92 on Windows), it will be set on the socket. This will prevent anyone else
93 from bind()'ing to our host/port for the duration of the test.
94 """
95
96 if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM:
97 if hasattr(socket, 'SO_REUSEADDR'):
98 if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1:
99 raise support.TestFailed("tests should never set the "
100 "SO_REUSEADDR socket option on "
101 "TCP/IP sockets!")
102 if hasattr(socket, 'SO_REUSEPORT'):
103 try:
104 if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1:
105 raise support.TestFailed("tests should never set the "
106 "SO_REUSEPORT socket option on "
107 "TCP/IP sockets!")
108 except OSError:
109 # Python's socket module was compiled using modern headers
110 # thus defining SO_REUSEPORT but this process is running
111 # under an older kernel that does not support SO_REUSEPORT.
112 pass
113 if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'):
114 sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
115
116 sock.bind((host, 0))
117 port = sock.getsockname()[1]
118 return port
119
120def bind_unix_socket(sock, addr):
121 """Bind a unix socket, raising SkipTest if PermissionError is raised."""

Callers 1

find_unused_portFunction · 0.85

Calls 4

getsockoptMethod · 0.45
setsockoptMethod · 0.45
bindMethod · 0.45
getsocknameMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…