Skip to content

Instantly share code, notes, and snippets.

@schmir
Created February 27, 2015 14:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schmir/8037974224514aead3f0 to your computer and use it in GitHub Desktop.
Save schmir/8037974224514aead3f0 to your computer and use it in GitHub Desktop.
def find_ip ():
# we get a UDP-socket for the TEST-networks reserved by IANA.
# It is highly unlikely, that there is special routing used
# for these networks, hence the socket later should give us
# the ip address of the default route.
# We're doing multiple tests, to guard against the computer being
# part of a test installation.
candidates = []
for test_ip in ["192.0.2.0", "198.51.100.0", "203.0.113.0"]:
s = socket.socket (socket.AF_INET, socket.SOCK_DGRAM)
s.connect ((test_ip, 80))
ip_addr = s.getsockname ()[0]
s.close ()
if ip_addr in candidates:
return ip_addr
candidates.append (ip_addr)
return candidates[0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment