python 根據ip 地址 獲取網卡掩碼和名字

這裏用到python 操作網卡比較好的模塊netifaces, 其他需求,可以仔細研究下這個模塊。

 

import netifaces

def get_netmask_through_nicip(nicip):
    """
        Get the netmask through give a ipaddr

        Args:
            nicip: ip addr

        Returns:
            netmask
    """
    netmask = ''
    nicfaces = netifaces.interfaces()

    for faces in nicfaces:
        message = netifaces.ifaddresses(faces)
        iface_addr = message.get(netifaces.AF_INET)
        if iface_addr:
            iface_dict = iface_addr[0]
            ipaddr = iface_dict.get('addr')
            if ipaddr == nicip:
                netmask = iface_dict.get('netmask')
    return netmask

def get_nicname_through_nicip(nicip):
    """
        Get the nic name through give a ipaddr

        Args:
            nicip: ip addr

        Returns:
            nic name
    """
    nicname = ''
    nicfaces = netifaces.interfaces()

    for faces in nicfaces:
        message = netifaces.ifaddresses(faces)
        iface_addr = message.get(netifaces.AF_INET)
        if iface_addr:
            iface_dict = iface_addr[0]
            ipaddr = iface_dict.get('addr')
            if ipaddr == nicip:
                nicname = faces
                break
    return nicname
 


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章