Skip to content

Instantly share code, notes, and snippets.

@pudquick
Created June 2, 2015 17:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pudquick/c2800ffd06890f67af23 to your computer and use it in GitHub Desktop.
Save pudquick/c2800ffd06890f67af23 to your computer and use it in GitHub Desktop.
This snippet gets you the default routing interface for a machine for general traffic
def default_interface():
# 203.0.113.1 is reserved in TEST-NET-3 per RFC5737
# Should never be local, essentially equal to "internet"
# This should get the 'default' interface
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# Uses UDP for instant 'connect' and port 9 for discard
# protocol: http://en.wikipedia.org/wiki/Discard_Protocol
s.connect(('203.0.113.1', 9))
client = s.getsockname()[0]
except socket.error:
client = "Unknown IP"
finally:
del s
return client
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment