How to use python requests with a server that has two IP addresses
Question: I have a Ubuntu server that has multiple IP addresses. As an example, how do I
set the correct IP address for outbound requests in a library like python
requests?


Answer: By default, this is not handled at application level, but by the operating
system. According to linux routing table, the OS will choose the appropriate
interface depending on the destination IP you are trying to reach.

You can edit linux routing table with the `ip route` command
([manual](http://linux.die.net/man/8/ip)).

However, you can tell your application to use a given network interface

Here is a related question and proposed solution with a raw socket:

    
    
    # From http://stackoverflow.com/questions/335607
    import socket
    s = socket.socket()
    s.bind(("127.0.0.1", 0))
    s.connect(("321.12.131.432", 80))
    

With requests, it should look like the following (untested)

    
    
    # From http://stackoverflow.com/questions/12585317
    import socket
    
    real_create_conn = socket.create_connection
    
    def set_src_addr(*args):
        address, timeout = args[0], args[1]
        source_address = ('IP_ADDR_TO_BIND_TO', 0)
        return real_create_conn(address, timeout, source_address)
    
    socket.create_connection = set_src_addr
    
    import requests
    r = requests.get('http://www.google.com')
    

