Python Glossary Русский

all Python 3socketfunction

socket.create_connection()

creating sockets

Connects to a TCP server at (host, port): it resolves the name itself and tries IPv4 and IPv6 addresses until one works.

Syntax

sock = socket.create_connection(address, timeout=GLOBAL_DEFAULT, source_address=None, *, all_errors=False)

Easier than a manual socket() plus connect(): you never pick the address family. Without timeout it uses getdefaulttimeout(), which is None, so connecting to a silent host hangs for minutes. The timeout stays on the returned socket and applies to every later recv/send, not just to connect. A closed port raises ConnectionRefusedError; all_errors=True (3.11+) raises an ExceptionGroup with every attempt's error.

Examples

import socket
with socket.create_server(('127.0.0.1', 0)) as srv:
    with socket.create_connection(srv.getsockname(), timeout=2) as cli:
        print(cli.gettimeout())  # → 2.0
        conn, _ = srv.accept()
        conn.close()
import socket
with socket.socket() as tmp:
    tmp.bind(('127.0.0.1', 0))
    port = tmp.getsockname()[1]  # порт свободен, но его никто не слушает
try:
    socket.create_connection(('127.0.0.1', port), timeout=1)
except ConnectionRefusedError as e:
    print(type(e).__name__)  # → ConnectionRefusedError
# Python 3.11+
import socket
with socket.socket() as tmp:
    tmp.bind(('127.0.0.1', 0))
    port = tmp.getsockname()[1]
try:
    socket.create_connection(('127.0.0.1', port), timeout=1, all_errors=True)
except* ConnectionRefusedError as eg:
    print(type(eg).__name__, len(eg.exceptions))  # → ExceptionGroup 1

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy