newb Q

Matthew Dixon Cowles matt at mondoinfo.com
Fri Jul 21 22:32:51 EDT 2000


In article <3978FD9D.B08460CB at mediaone.net>, Toy <gee308 at mediaone.net>
wrote:

> How can I make python issue the command, "ifconfig -a eth0", and then
> parse the data to grab the IP?  I would think that you could tell Python
> to look for the word, 'inet addr:"(is it different on different Unixes?)
> and then tell it to get a number right after 'inet addr' that looks like
> xx.x.xxx.xxx !!  Simple Q, but I'm new, thanks.

Something like this should work for you:

import os
import string
import re
import sys

def getMyAddr():
  p=os.popen("/sbin/ifconfig ep0")
  l=p.readline()
  while l<>"":
    if string.strip(l)[:5]=="inet ":
      matchObj=re.search("\d+.\d+.\d+.\d+",l)
      p.close()
      return matchObj.group(0)
    l=p.readline()
  p.close()
  return "not found"

def main():
  print getMyAddr()

if __name__=="__main__":
  main()

You'll also notice that the answer to your second question is yes. The
format of the output of ifconfig is different from Unix to Unix. The
above example works on FreeBSD. You will need to fiddle it some to get
it to work under Linux.

Another way to get the local IP is to use the functions in the socket
module:

>>> import socket
>>> socket.gethostbyaddr(socket.gethostname())[2][0]

But how to do that varies from machine to machine too. The code above
works correctly on my FreeBSD box but on my Linux laptop it returns
127.0.0.1. In order to make it work right on that machine, I need to
ask for the address of the hostname only, not the FQDN:

>>> socket.gethostbyaddr(socket.gethostname()
>>>   [:string.find(socket.gethostname(),".")])[2][0]

If there's a portable way of getting the local IP address, I don't know
what it is.

Regards,
Matt



More information about the Python-list mailing list