MCPcopy
hub / github.com/urllib3/urllib3 / create_connection

Function create_connection

src/urllib3/util/connection.py:27–90  ·  view source on GitHub ↗

Connect to *address* and return the socket object. Convenience function. Connect to *address* (a 2-tuple ``(host, port)``) and return the socket object. Passing the optional *timeout* parameter will set the timeout on the socket instance before attempting to connect. If no *timeo

(
    address: tuple[str, int],
    timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,
    source_address: tuple[str, int] | None = None,
    socket_options: _TYPE_SOCKET_OPTIONS | None = None,
)

Source from the content-addressed store, hash-verified

25# One additional modification is that we avoid binding to IPv6 servers
26# discovered in DNS if the system doesn't have IPv6 functionality.
27def create_connection(
28 address: tuple[str, int],
29 timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,
30 source_address: tuple[str, int] | None = None,
31 socket_options: _TYPE_SOCKET_OPTIONS | None = None,
32) -> socket.socket:
33 """Connect to *address* and return the socket object.
34
35 Convenience function. Connect to *address* (a 2-tuple ``(host,
36 port)``) and return the socket object. Passing the optional
37 *timeout* parameter will set the timeout on the socket instance
38 before attempting to connect. If no *timeout* is supplied, the
39 global default timeout setting returned by :func:`socket.getdefaulttimeout`
40 is used. If *source_address* is set it must be a tuple of (host, port)
41 for the socket to bind as a source address before making the connection.
42 An host of '' or port 0 tells the OS to use the default.
43 """
44
45 host, port = address
46 if host.startswith("["):
47 host = host.strip("[]")
48 err = None
49
50 # Using the value from allowed_gai_family() in the context of getaddrinfo lets
51 # us select whether to work with IPv4 DNS records, IPv6 records, or both.
52 # The original create_connection function always returns all records.
53 family = allowed_gai_family()
54
55 try:
56 host.encode("idna")
57 except UnicodeError:
58 raise LocationParseError(f"'{host}', label empty or too long") from None
59
60 for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
61 af, socktype, proto, canonname, sa = res
62 sock = None
63 try:
64 sock = socket.socket(af, socktype, proto)
65
66 # If provided, set socket level options before connecting.
67 _set_socket_options(sock, socket_options)
68
69 if timeout is not _DEFAULT_TIMEOUT:
70 sock.settimeout(timeout)
71 if source_address:
72 sock.bind(source_address)
73 sock.connect(sa)
74 # Break explicitly a reference cycle
75 err = None
76 return sock
77
78 except OSError as _:
79 err = _
80 if sock is not None:
81 sock.close()
82
83 if err is not None:
84 try:

Calls 6

allowed_gai_familyFunction · 0.85
LocationParseErrorClass · 0.85
_set_socket_optionsFunction · 0.85
settimeoutMethod · 0.45
connectMethod · 0.45
closeMethod · 0.45