1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2003
    Rep Power

    Question Ethernet card address Through Python or C

    I'm getting a problem to access the ethernet card address through python.
    There are two ways to do it:

    1. use "/sbin/ifconfig" and then do the string manipulation after taking the output using popen.

    >>> import os
    >>> p=os.popen("/sbin/ifconfig eth0")
    >>> t=p.read()
    >>> p.close()
    >>> import re
    >>> re.search("HWaddr ([0-9a-fA-F:]+)",t).group(1)

    BUT ....

    I'm not sure this will run in a language independent way. If I'm using Linux with German lang. then will this work? Actually it is the most crude way to arrive to the solution.

    I've progressed a little bit in the second way..

    2. use the socket and fcntl and IN (linux specific library).

    import socket
    import fcntl
    import IN
    s= socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    fd = s.fileno()
    But the last line raises error..

    Traceback (most recent call last):
    File "<stdin>", line 1, in ?
    IOError: [Errno 19] No such device

    Anyway I want in linux only not in a platform independent way. For windows I've already solved the problem with netbios library.

    I'll expect the solution in Linux platform in a language independent way.
  2. #2
  3. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2003
    Rep Power
    Try this:

    import socket
    import fcntl
    import string
    import sys
    import exceptions

    def getINTF():
    f = open("/proc/net/dev")
    ret = []
    iflist = f.readlines()
    for line in iflist:
    if ':' not in line:
    ifname, rest = words[0],words[1:]
    ifname = string.strip(ifname)
    return ret

    def hexy(n):
    return "%02x" % (ord(n))

    def getMAC(ifname):
    SIOCGIFHWADDR = 0x8927 # magic number
    ifname = string.strip(ifname)
    ifr = ifname + '\0'*(32-len(ifname))
    r= fcntl.ioctl(s.fileno(),SIOCGIFHWADDR,ifr)
    addr = map(hexy,r[18:24])
    ret = (':'.join(map(str, addr)))
    except IOError, e:
    ret = ''
    return ret

    list = getINTF()
    for i in list:
    print i, getIP(i), getMAC(i), getUP(i)

IMN logo majestic logo threadwatch logo seochat tools logo