[Tutor] Alternatives to get IP address of a computer : which one should I use ?

Shashwat Anand anand.shashwat at gmail.com
Tue Nov 24 11:26:31 CET 2009


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 ?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20091124/07e9ba9b/attachment.htm>


More information about the Tutor mailing list