added create_connection function to socket module (copied from python2.6)
This commit is contained in:
@@ -24,6 +24,39 @@ def socketpair(family=None, type=SOCK_STREAM, proto=0):
|
|||||||
a, b = __socketpair(family, type, proto)
|
a, b = __socketpair(family, type, proto)
|
||||||
return socket(a), socket(b)
|
return socket(a), socket(b)
|
||||||
|
|
||||||
|
|
||||||
|
_GLOBAL_DEFAULT_TIMEOUT = object()
|
||||||
|
|
||||||
|
def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT):
|
||||||
|
"""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 *timeout* is supplied, the
|
||||||
|
global default timeout setting returned by :func:`getdefaulttimeout`
|
||||||
|
is used.
|
||||||
|
"""
|
||||||
|
|
||||||
|
msg = "getaddrinfo returns an empty list"
|
||||||
|
host, port = address
|
||||||
|
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
|
||||||
|
af, socktype, proto, canonname, sa = res
|
||||||
|
sock = None
|
||||||
|
try:
|
||||||
|
sock = socket(af, socktype, proto)
|
||||||
|
if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
|
||||||
|
sock.settimeout(timeout)
|
||||||
|
sock.connect(sa)
|
||||||
|
return sock
|
||||||
|
|
||||||
|
except error, msg:
|
||||||
|
if sock is not None:
|
||||||
|
sock.close()
|
||||||
|
|
||||||
|
raise error, msg
|
||||||
|
|
||||||
|
|
||||||
def ssl(sock, certificate=None, private_key=None):
|
def ssl(sock, certificate=None, private_key=None):
|
||||||
from OpenSSL import SSL
|
from OpenSSL import SSL
|
||||||
context = SSL.Context(SSL.SSLv23_METHOD)
|
context = SSL.Context(SSL.SSLv23_METHOD)
|
||||||
|
Reference in New Issue
Block a user