2013년 12월 13일 금요일

[Python] Linux에서 이더넷 정보 가져오기

#!/usr/bin/env python
"""
ifconfig
exman@medialand.co.kr
"""

import string,socket,fcntl,IN

def ifconfig(ifname):
    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    ifr = ifname+'\0'*(16-len(ifname))+chr(socket.AF_INET)+15*'\0'

    try:
        r= fcntl.ioctl(s.fileno(),0x8927,ifr)
        hwaddr = map(ord,r[18:24])
    except IOError:
        s.close()
        return None

    try:
        r= fcntl.ioctl(s.fileno(),0x8915,ifr)
        addr = string.join(map(str,map(ord,r[20:24])),'.')
    except IOError:
        s.close()
        return None

    try:
        r= fcntl.ioctl(s.fileno(),0x8919,ifr)
        broadaddr = string.join(map(str,map(ord,r[20:24])),'.')
    except IOError:
        s.close()
        return None

    try:
        r= fcntl.ioctl(s.fileno(),0x891b,ifr)
        netmask = string.join(map(str,map(ord,r[20:24])),'.')
    except IOError:
        s.close()
        return None

    s.close()
    return hwaddr,addr,broadaddr,netmask

if __name__=='__main__':
    print ifconfig('eth0')
    print ifconfig('eth0:0')
    print ifconfig('eth0:1')
    print ifconfig('eth1')
    print ifconfig('lo')

댓글 없음:

댓글 쓰기