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, timeout=_GLOBAL_DEFAULT_TIMEOUT,
source_address=None, *, all_errors=False)
| 835 | _GLOBAL_DEFAULT_TIMEOUT = object() |
| 836 | |
| 837 | def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, |
| 838 | source_address=None, *, all_errors=False): |
| 839 | """Connect to *address* and return the socket object. |
| 840 | |
| 841 | Convenience function. Connect to *address* (a 2-tuple ``(host, |
| 842 | port)``) and return the socket object. Passing the optional |
| 843 | *timeout* parameter will set the timeout on the socket instance |
| 844 | before attempting to connect. If no *timeout* is supplied, the |
| 845 | global default timeout setting returned by :func:`getdefaulttimeout` |
| 846 | is used. If *source_address* is set it must be a tuple of (host, port) |
| 847 | for the socket to bind as a source address before making the connection. |
| 848 | A host of '' or port 0 tells the OS to use the default. When a connection |
| 849 | cannot be created, raises the last error if *all_errors* is False, |
| 850 | and an ExceptionGroup of all errors if *all_errors* is True. |
| 851 | """ |
| 852 | |
| 853 | host, port = address |
| 854 | exceptions = [] |
| 855 | for res in getaddrinfo(host, port, 0, SOCK_STREAM): |
| 856 | af, socktype, proto, canonname, sa = res |
| 857 | sock = None |
| 858 | try: |
| 859 | sock = socket(af, socktype, proto) |
| 860 | if timeout is not _GLOBAL_DEFAULT_TIMEOUT: |
| 861 | sock.settimeout(timeout) |
| 862 | if source_address: |
| 863 | sock.bind(source_address) |
| 864 | sock.connect(sa) |
| 865 | # Break explicitly a reference cycle |
| 866 | exceptions.clear() |
| 867 | return sock |
| 868 | |
| 869 | except error as exc: |
| 870 | if not all_errors: |
| 871 | exceptions.clear() # raise only the last error |
| 872 | exceptions.append(exc) |
| 873 | if sock is not None: |
| 874 | sock.close() |
| 875 | |
| 876 | if len(exceptions): |
| 877 | try: |
| 878 | if not all_errors: |
| 879 | raise exceptions[0] |
| 880 | raise ExceptionGroup("create_connection failed", exceptions) |
| 881 | finally: |
| 882 | # Break explicitly a reference cycle |
| 883 | exceptions.clear() |
| 884 | else: |
| 885 | raise error("getaddrinfo returns an empty list") |
| 886 | |
| 887 | |
| 888 | def has_dualstack_ipv6(): |
no test coverage detected
searching dependent graphs…