def get_iface_from_addr(addr):
"""Work out on which interface the provided address is configured."""
for iface in netifaces.interfaces():
addresses = netifaces.ifaddresses(iface)
for inet_type in addresses:
for _addr in addresses[inet_type]:
_addr = _addr['addr']
# link local
ll_key = re.compile("(.+)%.*")
raw = re.match(ll_key, _addr)
if raw:
_addr = raw.group(1)
if _addr == addr:
log("Address '%s' is configured on iface '%s'" %
(addr, iface))
return iface
msg = "Unable to infer net iface on which '%s' is configured" % (addr)
raise Exception(msg)
python类interfaces()的实例源码
def get_iface_from_addr(addr):
"""Work out on which interface the provided address is configured."""
for iface in netifaces.interfaces():
addresses = netifaces.ifaddresses(iface)
for inet_type in addresses:
for _addr in addresses[inet_type]:
_addr = _addr['addr']
# link local
ll_key = re.compile("(.+)%.*")
raw = re.match(ll_key, _addr)
if raw:
_addr = raw.group(1)
if _addr == addr:
log("Address '%s' is configured on iface '%s'" %
(addr, iface))
return iface
msg = "Unable to infer net iface on which '%s' is configured" % (addr)
raise Exception(msg)
def ipv4():
""" Get all IPv4 addresses for all interfaces. """
try:
from netifaces import interfaces, ifaddresses, AF_INET
# to not take into account loopback addresses (no interest here)
addresses = []
for interface in interfaces():
config = ifaddresses(interface)
# AF_INET is not always present
if AF_INET in config.keys():
for link in config[AF_INET]:
# loopback holds a 'peer' instead of a 'broadcast' address
if 'addr' in link.keys() and 'peer' not in link.keys():
addresses.append(link['addr'])
return addresses
except ImportError:
return []
def get_iface_from_addr(addr):
"""Work out on which interface the provided address is configured."""
for iface in netifaces.interfaces():
addresses = netifaces.ifaddresses(iface)
for inet_type in addresses:
for _addr in addresses[inet_type]:
_addr = _addr['addr']
# link local
ll_key = re.compile("(.+)%.*")
raw = re.match(ll_key, _addr)
if raw:
_addr = raw.group(1)
if _addr == addr:
log("Address '%s' is configured on iface '%s'" %
(addr, iface))
return iface
msg = "Unable to infer net iface on which '%s' is configured" % (addr)
raise Exception(msg)
def get_iface_from_addr(addr):
"""Work out on which interface the provided address is configured."""
for iface in netifaces.interfaces():
addresses = netifaces.ifaddresses(iface)
for inet_type in addresses:
for _addr in addresses[inet_type]:
_addr = _addr['addr']
# link local
ll_key = re.compile("(.+)%.*")
raw = re.match(ll_key, _addr)
if raw:
_addr = raw.group(1)
if _addr == addr:
log("Address '%s' is configured on iface '%s'" %
(addr, iface))
return iface
msg = "Unable to infer net iface on which '%s' is configured" % (addr)
raise Exception(msg)
def network(interface=None):
if interface:
try:
netifaces.ifaddresses(interface)
interfaces = [interface]
except ValueError:
return jsonify({"message": "interface {} not available".format(interface)}), 404
else:
interfaces = netifaces.interfaces()
data = dict()
for i in interfaces:
try:
data[i] = netifaces.ifaddresses(i)[2]
except KeyError:
data[i] = {"message": "AF_INET data missing"}
return jsonify(data)
def __init__(self,
data # Data suitable for this class
):
valid, message = data_is_valid(data)
if not valid:
raise ValueError("Invalid data: %s" % message)
self.cidrs = []
for iface in netifaces.interfaces():
ifaddrs = netifaces.ifaddresses(iface)
if netifaces.AF_INET in ifaddrs:
for ifaddr in ifaddrs[netifaces.AF_INET]:
if 'addr' in ifaddr:
self.cidrs.append(ipaddr.IPNetwork(ifaddr['addr']))
if netifaces.AF_INET6 in ifaddrs:
for ifaddr in ifaddrs[netifaces.AF_INET6]:
if 'addr' in ifaddr:
#add v6 but remove stuff like %eth0 that gets thrown on end of some addrs
self.cidrs.append(ipaddr.IPNetwork(ifaddr['addr'].split('%')[0]))
def get_iface_from_addr(addr):
"""Work out on which interface the provided address is configured."""
for iface in netifaces.interfaces():
addresses = netifaces.ifaddresses(iface)
for inet_type in addresses:
for _addr in addresses[inet_type]:
_addr = _addr['addr']
# link local
ll_key = re.compile("(.+)%.*")
raw = re.match(ll_key, _addr)
if raw:
_addr = raw.group(1)
if _addr == addr:
log("Address '%s' is configured on iface '%s'" %
(addr, iface))
return iface
msg = "Unable to infer net iface on which '%s' is configured" % (addr)
raise Exception(msg)
def get_iface_from_addr(addr):
"""Work out on which interface the provided address is configured."""
for iface in netifaces.interfaces():
addresses = netifaces.ifaddresses(iface)
for inet_type in addresses:
for _addr in addresses[inet_type]:
_addr = _addr['addr']
# link local
ll_key = re.compile("(.+)%.*")
raw = re.match(ll_key, _addr)
if raw:
_addr = raw.group(1)
if _addr == addr:
log("Address '%s' is configured on iface '%s'" %
(addr, iface))
return iface
msg = "Unable to infer net iface on which '%s' is configured" % (addr)
raise Exception(msg)
def get_iface_from_addr(addr):
"""Work out on which interface the provided address is configured."""
for iface in netifaces.interfaces():
addresses = netifaces.ifaddresses(iface)
for inet_type in addresses:
for _addr in addresses[inet_type]:
_addr = _addr['addr']
# link local
ll_key = re.compile("(.+)%.*")
raw = re.match(ll_key, _addr)
if raw:
_addr = raw.group(1)
if _addr == addr:
log("Address '%s' is configured on iface '%s'" %
(addr, iface))
return iface
msg = "Unable to infer net iface on which '%s' is configured" % (addr)
raise Exception(msg)
def get_iface_from_addr(addr):
"""Work out on which interface the provided address is configured."""
for iface in netifaces.interfaces():
addresses = netifaces.ifaddresses(iface)
for inet_type in addresses:
for _addr in addresses[inet_type]:
_addr = _addr['addr']
# link local
ll_key = re.compile("(.+)%.*")
raw = re.match(ll_key, _addr)
if raw:
_addr = raw.group(1)
if _addr == addr:
log("Address '%s' is configured on iface '%s'" %
(addr, iface))
return iface
msg = "Unable to infer net iface on which '%s' is configured" % (addr)
raise Exception(msg)
def get_host_devices(iface_prefix=''):
rst = {}
for ifacename in netifaces.interfaces():
if not ifacename.startswith(iface_prefix):
continue
addrs = netifaces.ifaddresses(ifacename)
if netifaces.AF_INET in addrs and netifaces.AF_LINK in addrs:
ips = [addr['addr'] for addr in addrs[netifaces.AF_INET]]
for ip in ips:
if is_ip4_loopback(ip):
break
else:
rst[ifacename] = {'INET': addrs[netifaces.AF_INET],
'LINK': addrs[netifaces.AF_LINK]}
return rst
def get_interface_addresses(logger):
import StaticUPnP_Settings
interface_config = Namespace(**StaticUPnP_Settings.interfaces)
ip_addresses = StaticUPnP_Settings.ip_addresses
if len(ip_addresses) == 0:
import netifaces
ifs = netifaces.interfaces()
if len(interface_config.include) > 0:
ifs = interface_config.include
if len(interface_config.exclude) > 0:
for iface in interface_config.exclude:
ifs.remove(iface)
for i in ifs:
addrs = netifaces.ifaddresses(i)
if netifaces.AF_INET in addrs:
for addr in addrs[netifaces.AF_INET]:
ip_addresses.append(addr['addr'])
logger.info("Regestering multicast on %s: %s"%(i, addr['addr']))
return ip_addresses
def internal_ip(pl, interface='auto', ipv=4):
family = netifaces.AF_INET6 if ipv == 6 else netifaces.AF_INET
if interface == 'auto':
try:
interface = next(iter(sorted(netifaces.interfaces(), key=_interface_key, reverse=True)))
except StopIteration:
pl.info('No network interfaces found')
return None
elif interface == 'default_gateway':
try:
interface = netifaces.gateways()['default'][family][1]
except KeyError:
pl.info('No default gateway found for IPv{0}', ipv)
return None
addrs = netifaces.ifaddresses(interface)
try:
return addrs[family][0]['addr']
except (KeyError, IndexError):
pl.info("No IPv{0} address found for interface {1}", ipv, interface)
return None
def configure(protocol, port, pipes, interface):
remove_all()
reactor.addSystemEventTrigger('after', 'shutdown', remove_all)
# gets default (outward-facing) network interface (e.g. deciding which of
# eth0, eth1, wlan0 is being used by the system to connect to the internet)
if interface == "auto":
interface = netifaces.gateways()['default'][netifaces.AF_INET][1]
else:
if interface not in netifaces.interfaces():
raise ValueError("Given interface does not exist.", interface)
add(protocol, port, interface)
manager = libnetfilter_queue.Manager()
manager.bind(UP_QUEUE, packet_handler(manager, pipes.up))
manager.bind(DOWN_QUEUE, packet_handler(manager, pipes.down))
reader = abstract.FileDescriptor()
reader.doRead = manager.process
reader.fileno = lambda: manager.fileno
reactor.addReader(reader)
def get_iface_from_addr(addr):
"""Work out on which interface the provided address is configured."""
for iface in netifaces.interfaces():
addresses = netifaces.ifaddresses(iface)
for inet_type in addresses:
for _addr in addresses[inet_type]:
_addr = _addr['addr']
# link local
ll_key = re.compile("(.+)%.*")
raw = re.match(ll_key, _addr)
if raw:
_addr = raw.group(1)
if _addr == addr:
log("Address '%s' is configured on iface '%s'" %
(addr, iface))
return iface
msg = "Unable to infer net iface on which '%s' is configured" % (addr)
raise Exception(msg)
def get_iface_from_addr(addr):
"""Work out on which interface the provided address is configured."""
for iface in netifaces.interfaces():
addresses = netifaces.ifaddresses(iface)
for inet_type in addresses:
for _addr in addresses[inet_type]:
_addr = _addr['addr']
# link local
ll_key = re.compile("(.+)%.*")
raw = re.match(ll_key, _addr)
if raw:
_addr = raw.group(1)
if _addr == addr:
log("Address '%s' is configured on iface '%s'" %
(addr, iface))
return iface
msg = "Unable to infer net iface on which '%s' is configured" % (addr)
raise Exception(msg)
def get_ip_address(iface):
"""Get IP address of the interface connected to the network.
If there is no such an interface, then localhost is returned.
"""
if iface not in netifaces.interfaces():
LOG.warning("Can't find interface '%s' in the host list of interfaces",
iface)
return '127.0.0.1'
address_family = netifaces.AF_INET
if address_family not in netifaces.ifaddresses(iface):
LOG.warning("Interface '%s' doesnt configured with ipv4 address",
iface)
return '127.0.0.1'
for ifaddress in netifaces.ifaddresses(iface)[address_family]:
if 'addr' in ifaddress:
return ifaddress['addr']
else:
LOG.warning("Can't find ip addr for interface '%s'", iface)
return '127.0.0.1'
3_11_extract_ipv6_prefix.py 文件源码
项目:Python-Network-Programming-Cookbook-Second-Edition
作者: PacktPublishing
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
def extract_ipv6_info():
""" Extracts IPv6 information"""
print ("IPv6 support built into Python: %s" %socket.has_ipv6)
for interface in ni.interfaces():
all_addresses = ni.ifaddresses(interface)
print ("Interface %s:" %interface)
for family,addrs in all_addresses.items():
fam_name = ni.address_families[family]
for addr in addrs:
if fam_name == 'AF_INET6':
addr = addr['addr']
has_eth_string = addr.split("%eth")
if has_eth_string:
addr = addr.split("%eth")[0]
try:
print (" IP Address: %s" %na.IPNetwork(addr))
print (" IP Version: %s" %na.IPNetwork(addr).version)
print (" IP Prefix length: %s" %na.IPNetwork(addr).prefixlen)
print (" Network: %s" %na.IPNetwork(addr).network)
print (" Broadcast: %s" %na.IPNetwork(addr).broadcast)
except Exception as e:
print ("Skip Non-IPv6 Interface")
3_10_check_ipv6_support.py 文件源码
项目:Python-Network-Programming-Cookbook-Second-Edition
作者: PacktPublishing
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def inspect_ipv6_support():
""" Find the ipv6 address"""
print ("IPV6 support built into Python: %s" %socket.has_ipv6)
ipv6_addr = {}
for interface in ni.interfaces():
all_addresses = ni.ifaddresses(interface)
print ("Interface %s:" %interface)
for family,addrs in all_addresses.items():
fam_name = ni.address_families[family]
print (' Address family: %s' % fam_name)
for addr in addrs:
if fam_name == 'AF_INET6':
ipv6_addr[interface] = addr['addr']
print (' Address : %s' % addr['addr'])
nmask = addr.get('netmask', None)
if nmask:
print (' Netmask : %s' % nmask)
bcast = addr.get('broadcast', None)
if bcast:
print (' Broadcast: %s' % bcast)
if ipv6_addr:
print ("Found IPv6 address: %s" %ipv6_addr)
else:
print ("No IPv6 interface found!")
def get_iface_from_addr(addr):
"""Work out on which interface the provided address is configured."""
for iface in netifaces.interfaces():
addresses = netifaces.ifaddresses(iface)
for inet_type in addresses:
for _addr in addresses[inet_type]:
_addr = _addr['addr']
# link local
ll_key = re.compile("(.+)%.*")
raw = re.match(ll_key, _addr)
if raw:
_addr = raw.group(1)
if _addr == addr:
log("Address '%s' is configured on iface '%s'" %
(addr, iface))
return iface
msg = "Unable to infer net iface on which '%s' is configured" % (addr)
raise Exception(msg)
def get_iface_from_addr(addr):
"""Work out on which interface the provided address is configured."""
for iface in netifaces.interfaces():
addresses = netifaces.ifaddresses(iface)
for inet_type in addresses:
for _addr in addresses[inet_type]:
_addr = _addr['addr']
# link local
ll_key = re.compile("(.+)%.*")
raw = re.match(ll_key, _addr)
if raw:
_addr = raw.group(1)
if _addr == addr:
log("Address '%s' is configured on iface '%s'" %
(addr, iface))
return iface
msg = "Unable to infer net iface on which '%s' is configured" % (addr)
raise Exception(msg)
def get_iface_from_addr(addr):
"""Work out on which interface the provided address is configured."""
for iface in netifaces.interfaces():
addresses = netifaces.ifaddresses(iface)
for inet_type in addresses:
for _addr in addresses[inet_type]:
_addr = _addr['addr']
# link local
ll_key = re.compile("(.+)%.*")
raw = re.match(ll_key, _addr)
if raw:
_addr = raw.group(1)
if _addr == addr:
log("Address '%s' is configured on iface '%s'" %
(addr, iface))
return iface
msg = "Unable to infer net iface on which '%s' is configured" % (addr)
raise Exception(msg)
def get_iface_from_addr(addr):
"""Work out on which interface the provided address is configured."""
for iface in netifaces.interfaces():
addresses = netifaces.ifaddresses(iface)
for inet_type in addresses:
for _addr in addresses[inet_type]:
_addr = _addr['addr']
# link local
ll_key = re.compile("(.+)%.*")
raw = re.match(ll_key, _addr)
if raw:
_addr = raw.group(1)
if _addr == addr:
log("Address '%s' is configured on iface '%s'" %
(addr, iface))
return iface
msg = "Unable to infer net iface on which '%s' is configured" % (addr)
raise Exception(msg)
def in6_getifaddr():
"""
Returns a list of 3-tuples of the form (addr, scope, iface) where
'addr' is the address of scope 'scope' associated to the interface
'ifcace'.
This is the list of all addresses of all interfaces available on
the system.
"""
ret = []
interfaces = get_if_list()
for i in interfaces:
addrs = netifaces.ifaddresses(i)
if netifaces.AF_INET6 not in addrs:
continue
for a in addrs[netifaces.AF_INET6]:
addr = a['addr'].split('%')[0]
scope = scapy.utils6.in6_getscope(addr)
ret.append((addr, scope, i))
return ret
def get_iface_from_addr(addr):
"""Work out on which interface the provided address is configured."""
for iface in netifaces.interfaces():
addresses = netifaces.ifaddresses(iface)
for inet_type in addresses:
for _addr in addresses[inet_type]:
_addr = _addr['addr']
# link local
ll_key = re.compile("(.+)%.*")
raw = re.match(ll_key, _addr)
if raw:
_addr = raw.group(1)
if _addr == addr:
log("Address '%s' is configured on iface '%s'" %
(addr, iface))
return iface
msg = "Unable to infer net iface on which '%s' is configured" % (addr)
raise Exception(msg)
def get_iface_from_addr(addr):
"""Work out on which interface the provided address is configured."""
for iface in netifaces.interfaces():
addresses = netifaces.ifaddresses(iface)
for inet_type in addresses:
for _addr in addresses[inet_type]:
_addr = _addr['addr']
# link local
ll_key = re.compile("(.+)%.*")
raw = re.match(ll_key, _addr)
if raw:
_addr = raw.group(1)
if _addr == addr:
log("Address '%s' is configured on iface '%s'" %
(addr, iface))
return iface
msg = "Unable to infer net iface on which '%s' is configured" % (addr)
raise Exception(msg)
def get_lo_alias_addr():
# check all interfaces an try to find one with address 127.0.0.1
# If that interface has another address, that's the one we need.
ifname_loopback = None
for interface in netifaces.interfaces():
ip_addresses = []
interface_addresses = netifaces.ifaddresses(interface)
if netifaces.AF_INET not in interface_addresses:
continue
for address_data in interface_addresses[netifaces.AF_INET]:
if address_data.get('addr') == '127.0.0.1':
ifname_loopback = interface
elif address_data.get('addr'):
ip_addresses.append(address_data.get('addr'))
if interface == ifname_loopback and ip_addresses:
return ip_addresses[0]
def get_iface_from_addr(addr):
"""Work out on which interface the provided address is configured."""
for iface in netifaces.interfaces():
addresses = netifaces.ifaddresses(iface)
for inet_type in addresses:
for _addr in addresses[inet_type]:
_addr = _addr['addr']
# link local
ll_key = re.compile("(.+)%.*")
raw = re.match(ll_key, _addr)
if raw:
_addr = raw.group(1)
if _addr == addr:
log("Address '%s' is configured on iface '%s'" %
(addr, iface))
return iface
msg = "Unable to infer net iface on which '%s' is configured" % (addr)
raise Exception(msg)
multiport_stress.py 文件源码
项目:avocado-misc-tests
作者: avocado-framework-tests
项目源码
文件源码
阅读 19
收藏 0
点赞 0
评论 0
def setUp(self):
'''
To check and install dependencies for the test
'''
self.host_interfaces = self.params.get("host_interfaces",
default="").split(",")
if not self.host_interfaces:
self.cancel("user should specify host interfaces")
smm = SoftwareManager()
if distro.detect().name == 'Ubuntu':
pkg = 'iputils-ping'
else:
pkg = 'iputils'
if not smm.check_installed(pkg) and not smm.install(pkg):
self.cancel("Package %s is needed to test" % pkg)
self.peer_ips = self.params.get("peer_ips",
default="").split(",")
interfaces = netifaces.interfaces()
for self.host_interface in self.host_interfaces:
if self.host_interface not in interfaces:
self.cancel("interface is not available")
self.count = self.params.get("count", default="1000")