newb Q

Toy gee308 at mediaone.net
Sat Jul 22 02:42:15 EDT 2000


Thanks for showing me how to do that.  I tried to edit something, but it
didn't work, I'll show you:


def getMyAddr():
  object = raw_input(Which device is connect to the internet(i.e. ppp0, eth0,
ne3: ")
  p=os.popen("/sbin/ifconfig",object)

Is it possible to do that?  Will it work with os.system?  What are the
differences bewteen using os.popen and os.system?  Thanks for your time.
BTW, I only compared OpenBSD 2.7, Linux 2.2.15, and FreeBSD 4.0, but it seems
if you do the string search  on ifconfig with find text on 1 line beginning
with inet and ending with mask, It looks like you can get the IP from those 3
machines.(of coure I still can't write some code to actually do it).  Thanks
again.
Jason Toy



Matthew Dixon Cowles wrote:

> 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