How to get Network Interface Card names in Python?

后端 未结 9 1833
灰色年华
灰色年华 2020-12-06 09:36

I am totally new to python programming so please be patient with me.

Is there anyway to get the names of the NIC cards in the machine etc. eth0, lo? If so how do you

9条回答
  •  忘掉有多难
    2020-12-06 09:51

    Using python's ctypes you can make a call to the C library function getifaddrs:

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    from ctypes import *
    
    class Sockaddr(Structure):
        _fields_ = [('sa_family', c_ushort), ('sa_data', c_char * 14)]
    
    class Ifa_Ifu(Union):
        _fields_ = [('ifu_broadaddr', POINTER(Sockaddr)),
                    ('ifu_dstaddr', POINTER(Sockaddr))]
    
    class Ifaddrs(Structure):
        pass
    
    Ifaddrs._fields_ = [('ifa_next', POINTER(Ifaddrs)), ('ifa_name', c_char_p),
                        ('ifa_flags', c_uint), ('ifa_addr', POINTER(Sockaddr)),
                        ('ifa_netmask', POINTER(Sockaddr)), ('ifa_ifu', Ifa_Ifu),
                        ('ifa_data', c_void_p)]
    
    
    def get_interfaces():
        libc = CDLL('libc.so.6')
        libc.getifaddrs.restype = c_int
        ifaddr_p = pointer(Ifaddrs())
        ret = libc.getifaddrs(pointer((ifaddr_p)))
        interfaces = set()
        head = ifaddr_p
        while ifaddr_p:
            interfaces.add(ifaddr_p.contents.ifa_name)
            ifaddr_p = ifaddr_p.contents.ifa_next
        libc.freeifaddrs(head) 
        return interfaces
    
    if __name__ == "__main__":
        print(get_interfaces())
    

    Do note though this method is not portable.

提交回复
热议问题