这里用到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