title: Python: Get local IP-Address used to send IP data to a specific remote IP-Address
body: <p>I am using a Python script to send UDP packets to a server which will register my script to receive notifications from the server. The protocol requires that I send my own IP-Address and port on which I want to receive these notifications, so this should be an address that is reachable from the server's network.</p>
  
  <p>Solutions should at least work on Windows XP and above and preferably Mac OS X, as this is my development platform.</p>
  
  <p>The first step is to get the IP-Address of any of my interfaces. I am currently using the commonly suggested approach of resolving the machines own host name:</p>
  
  <pre><code>def get_local_address():
      return socket.gethostbyname(socket.gethostname())
  </code></pre>
  
  <p>This only works sometimes. Currently it returns <code>172.16.249.1</code>, which is the address of a virtual interface used by VM Ware, so this is a problem.</p>
  
  <p>Much better would be a way to get the IP-Address of the default interface, which should be the right one most of the time.</p>
  
  <p>Even better would be a way to get the actual IP-Address used to connect to the server by a connection-oriented protocol like TCP. I can actually get that address, but not without attempting to open the connection:</p>
  
  <pre><code>def get_address_to_connect_to(server_addr):
      non_open_port = 50000
      s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  
      try:
          s.connect((server_addr, non_open_port))
      except socket.error:
          pass
      else:
          s.close() # just in case
  
      return s.getsockname()[0]
  </code></pre>
  
  <p>This will block until some TCP timeout has been reached in the case that the server is unreachable or an evil firewall in between is blocking ICMP packets. Is there a better way to get that information?</p>