summaryrefslogtreecommitdiff
path: root/Lib/socket.py
diff options
context:
space:
mode:
authorGregory P. Smith <greg@mad-scientist.com>2010-01-03 01:29:44 +0000
committerGregory P. Smith <greg@mad-scientist.com>2010-01-03 01:29:44 +0000
commit79a3eb1058057185cb901b0f5f67fea05494e1fb (patch)
tree09456d423e27dfe76cf46079f944ae877f16e492 /Lib/socket.py
parent7f8ebdbad54015074c71786abbfa7ea74fe69c56 (diff)
downloadcpython-git-79a3eb1058057185cb901b0f5f67fea05494e1fb.tar.gz
Adds an optional source_address parameter to socket.create_connection().
For use by issue3972.
Diffstat (limited to 'Lib/socket.py')
-rw-r--r--Lib/socket.py12
1 files changed, 9 insertions, 3 deletions
diff --git a/Lib/socket.py b/Lib/socket.py
index b37914441d..9b4bedaafb 100644
--- a/Lib/socket.py
+++ b/Lib/socket.py
@@ -24,7 +24,8 @@ 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
+create_connection() -- connects to an address, with an optional timeout and
+ optional source address.
[*] not available on all platforms!
@@ -531,7 +532,8 @@ class _fileobject(object):
_GLOBAL_DEFAULT_TIMEOUT = object()
-def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT):
+def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT,
+ source_address=None):
"""Connect to *address* and return the socket object.
Convenience function. Connect to *address* (a 2-tuple ``(host,
@@ -539,7 +541,9 @@ def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT):
*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.
+ is used. If *source_address* is set it must be a tuple of (host, port)
+ for the socket to bind as a source address before making the connection.
+ An host of '' or port 0 tells the OS to use the default.
"""
msg = "getaddrinfo returns an empty list"
@@ -551,6 +555,8 @@ def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT):
sock = socket(af, socktype, proto)
if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
sock.settimeout(timeout)
+ if source_address:
+ sock.bind(source_address)
sock.connect(sa)
return sock