Skip to content

[py] free_port() IPv6 fallback socket not closed when bind fails #16164

@VbhvGupta

Description

@VbhvGupta

try:
# IPv4
free_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
free_socket.bind(("127.0.0.1", 0))
except OSError:
if free_socket:
free_socket.close()
# IPv6
try:
free_socket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
free_socket.bind(("::1", 0))
except OSError:
raise RuntimeError("Can't find free port (Unable to bind to IPv4 or IPv6)")

  • If the free_port() function's attempt to bind to both IPv4 and IPv6 fails, the IPv6 socket is not closed before raising RunTimeError.

  • Running the above code in a loop (e.g., inside a for i in range(1000): ...) may eventually exhaust file descriptors on your system.

  • FIX : Adding free_socket.close() in the IPv6 exception handler, just like in the IPv4 exception handler here:

    if free_socket:
    free_socket.close()


This is not normally triggered in routine environments, but can lead to real problems in test suites, CI environments, or repeated runs.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions