Advertisement
Guest User

Socket.py excerpt create_connection

a guest
Jul 7th, 2014
290
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.48 KB | None | 0 0
  1. def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT,
  2.                       source_address=None):
  3.     """Connect to *address* and return the socket object.
  4.  
  5.    Convenience function.  Connect to *address* (a 2-tuple ``(host,
  6.    port)``) and return the socket object.  Passing the optional
  7.    *timeout* parameter will set the timeout on the socket instance
  8.    before attempting to connect.  If no *timeout* is supplied, the
  9.    global default timeout setting returned by :func:`getdefaulttimeout`
  10.    is used.  If *source_address* is set it must be a tuple of (host, port)
  11.    for the socket to bind as a source address before making the connection.
  12.    An host of '' or port 0 tells the OS to use the default.
  13.    """
  14.     print(str(address))
  15.     print(str(timeout))
  16.     print(str(source_address))
  17.     host, port = address
  18.     err = None
  19.     for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  20.         af, socktype, proto, canonname, sa = res
  21.         sock = None
  22.         try:
  23.             sock = socket(af, socktype, proto)
  24.             if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
  25.                 sock.settimeout(timeout)
  26.             if source_address:
  27.                 sock.bind(source_address)
  28.             sock.connect(sa)
  29.             return sock
  30.  
  31.         except error as _:
  32.             err = _
  33.             if sock is not None:
  34.                 sock.close()
  35.  
  36.     if err is not None:
  37.         raise err
  38.     else:
  39.         raise error("getaddrinfo returns an empty list")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement