I was going through a python scrip woof ( http://www.home.unix-ag.org/simon/woof ) and there was a portion of the code dedicated to get IP address
def find_ip (): if sys.platform == "cygwin": ipcfg = os.popen("ipconfig").readlines() for l in ipcfg: try: candidat = l.split(":")[1].strip() if candidat[0].isdigit(): break except: pass return candidat os.environ["PATH"] = "/sbin:/usr/sbin:/usr/local/sbin:" + os.environ["PATH"] platform = os.uname()[0]; if platform == "Linux": netstat = commands.getoutput ("LC_MESSAGES=C netstat -rn") defiface = [i.split ()[-1] for i in netstat.split ('\n') if i.split ()[0] == "0.0.0.0"] elif platform in ("Darwin", "FreeBSD", "NetBSD"): netstat = commands.getoutput ("LC_MESSAGES=C netstat -rn") defiface = [i.split ()[-1] for i in netstat.split ('\n') if len(i) > 2 and i.split ()[0] == "default"] elif platform == "SunOS": netstat = commands.getoutput ("LC_MESSAGES=C netstat -arn") defiface = [i.split ()[-1] for i in netstat.split ('\n') if len(i) > 2 and i.split ()[0] == "0.0.0.0"] else: print >>sys.stderr, "Unsupported platform; please add support for your platform in find_ip()."; return None if not defiface: return None if platform == "Linux": ifcfg = commands.getoutput ("LC_MESSAGES=C ifconfig " + defiface[0]).split ("inet addr:") elif platform in ("Darwin", "FreeBSD", "SunOS", "NetBSD"): ifcfg = commands.getoutput ("LC_MESSAGES=C ifconfig " + defiface[0]).split ("inet ") if len (ifcfg) != 2: return None ip_addr = ifcfg[1].split ()[0] # sanity check try: ints = [ i for i in ip_addr.split (".") if 0 <= int(i) <= 255] if len (ints) != 4: return None except ValueError: return None return ip_addr It gets OS name, run netstat -rn, gets the interface name via it ('en' in my case i.e. Darwin, and then run ifconfig and split it via 'inet ' and gets the IP and do a check. Nice !! However if I want to get my IP I can get it via: >>>socket.gethostbyname(socket.gethostname()) I want to know why the above approach is followed, is it so because of a check via network ?
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor