summaryrefslogtreecommitdiffstats
path: root/Lib/socket.py
diff options
context:
space:
mode:
Diffstat (limited to 'Lib/socket.py')
-rw-r--r--Lib/socket.py33
1 files changed, 30 insertions, 3 deletions
diff --git a/Lib/socket.py b/Lib/socket.py
index 3fe6ec5..8dd2383 100644
--- a/Lib/socket.py
+++ b/Lib/socket.py
@@ -24,6 +24,7 @@ inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89)
ssl() -- secure socket layer support (only available if configured)
socket.getdefaulttimeout() -- get the default timeout value
socket.setdefaulttimeout() -- set the default timeout value
+create_connection() -- connects to an address, with an optional timeout
[*] not available on all platforms!
@@ -139,8 +140,6 @@ class _closedsocket(object):
__slots__ = []
def _dummy(*args):
raise error(EBADF, 'Bad file descriptor')
- def close(self):
- pass
# All _delegate_methods must also be initialized here.
send = recv = recv_into = sendto = recvfrom = recvfrom_into = _dummy
__getattr__ = _dummy
@@ -159,7 +158,6 @@ class _socketobject(object):
setattr(self, method, getattr(_sock, method))
def close(self):
- self._sock.close()
self._sock = _closedsocket()
dummy = self._sock._dummy
for method in _delegate_methods:
@@ -414,3 +412,32 @@ class _fileobject(object):
if not line:
raise StopIteration
return line
+
+
+def create_connection(address, timeout=None):
+ """Connect to address (host, port) with an optional timeout.
+
+ Provides access to socketobject timeout for higher-level
+ protocols. Passing a timeout will set the timeout on the
+ socket instance (if not present, or passed as None, the
+ default global timeout setting will be 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 None:
+ sock.settimeout(timeout)
+ sock.connect(sa)
+ return sock
+
+ except error as err:
+ msg = err
+ if sock is not None:
+ sock.close()
+
+ raise error(msg)