What's a good way to get my IP from Python?

Charles G Waldman cgw at fnal.gov
Tue Aug 10 14:17:13 EDT 1999


Aaron Rhodes writes:
 > Hello,
 > 
 > Does anyone know of a really good way to determine the
 > IP address of the ethernet cards on a Linux system
 > using Python only (i.e. no C code/parsing external binaries, etc.) ?
 > 

How about this?   I don't know if it's "really good" but it works, and 
it shows you how to do IOCTL's from Python.  (Lately, folks on the
list have been suggesting writing a new extension module whenever you
need to do such a thing, but this is IMO unattractive from the point
of view of easy redistribution of code).

The only external dependency is on the file /proc/net/dev to get the
names of all present network interfaces.  (This will also pick up
loopback, dummy, ppp, and any other interface types).  If you know you
are only interested in eth*, you could just use a loop where ifname
goes from eth0 to ethN (assuming you don't have more than N NIC's) and
just catch exceptions where there is "no such device".  However, since
you said you are interested in Linux, /proc/net/dev is a pretty
reasonable thing to look at.  The linux "ifconfig -a" command gets its
interface list the same way.

There are some hardcoded constants in the code below.  32 is the size
of "struct ifreq" (see /usr/include/linux/if.h) and 20:24 are the
offsets of the inet address within this structure

These offsets are correct for kernel 2.2.  These offsets will need to
be tweaked for older kernel versions.  To create a truly portable
version of this code, you'd have to look at os.uname()[3] and adjust
the offsets appropriately.

A purist would probably use the struct module rather than slicing
strings.




#!/usr/bin/env python

import string
import socket
import fcntl
import IN

iflist = open("/proc/net/dev").readlines()

s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

for line in iflist:
    if ':' not in line:
        continue
    words=string.split(line,':')
    ifname, rest = words[0],words[1:]
    ifname = string.strip(ifname)
    
    print ifname,

    ifr = ifname+'\0'*(32-len(ifname))
    r= fcntl.ioctl(s.fileno(),IN.SIOCGIFADDR,ifr)
    addr = map(ord,r[20:24])

    print addr
    




More information about the Python-list mailing list