When source_address of python socket.create_connection is used? [closed]

As the documentation says:

If supplied, source_address must be a 2-tuple (host, port) for the socket to bind to as its source address before connecting. If host or port are ‘’ or 0 respectively the OS default behavior will be used.

In other words, it’s used when you need to bind the socket before connecting. If you don’t know why you’d ever need to do that, you don’t need to do it. But here’s a brief sketch of an example: An FTP server needs to be able to make an outgoing data connection on the same interface as the incoming control connection. You can do that by binding the same local address that the control connection has. So:

def make_data_conn(controlconn, port, timeout):
    return socket.create_connection((controlconn.getpeername()[0], port),
                                    timeout,
                                    (controlconn.getsockname()[0], 0))

Leave a Comment