#!/usr/bin/env python import socket 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] if ip_addr in candidates: return ip_addr candidates.append (ip_addr) return candidates[0] if __name__=='__main__': print find_ip ()