本文整理汇总了Python中ipaddress.IPv4Network方法的典型用法代码示例。如果您正苦于以下问题:Python ipaddress.IPv4Network方法的具体用法?Python ipaddress.IPv4Network怎么用?Python ipaddress.IPv4Network使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ipaddress
的用法示例。
在下文中一共展示了ipaddress.IPv4Network方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: find_internal_ip_on_device_network
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Network [as 别名]
def find_internal_ip_on_device_network(upnp_dev: upnpclient.upnp.Device) -> str:
"""
For a given UPnP device, return the internal IP address of this host machine that can
be used for a NAT mapping.
"""
parsed_url = urlparse(upnp_dev.location)
# Get an ipaddress.IPv4Network instance for the upnp device's network.
upnp_dev_net = ipaddress.ip_network(parsed_url.hostname + "/24", strict=False)
for iface in netifaces.interfaces():
for family, addresses in netifaces.ifaddresses(iface).items():
# TODO: Support IPv6 addresses as well.
if family != netifaces.AF_INET:
continue
for item in addresses:
if ipaddress.ip_address(item["addr"]) in upnp_dev_net:
return item["addr"]
raise NoInternalAddressMatchesDevice(device_hostname=parsed_url.hostname)
示例2: _validate_cidr
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Network [as 别名]
def _validate_cidr(self, rule):
"""Validate the cidr block in a rule.
Returns:
True: Upon successful completion.
Raises:
SpinnakerSecurityGroupCreationFailed: CIDR definition is invalid or
the network range is too wide.
"""
try:
network = ipaddress.IPv4Network(rule['app'])
except (ipaddress.NetmaskValueError, ValueError) as error:
raise SpinnakerSecurityGroupCreationFailed(error)
self.log.debug('Validating CIDR: %s', network.exploded)
return True
示例3: prehandle_roa
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Network [as 别名]
def prehandle_roa(asn_table: dict, args):
roa = route_to_roa(asn_table)
max_prefixlen = IPv4Network(0).max_prefixlen
roa4 = filter(lambda item: isinstance(item["prefix"], IPv4Network), roa)
roa6 = filter(lambda item: isinstance(item["prefix"], IPv6Network), roa)
if args.ipv4:
roa6 = []
elif args.ipv6:
roa4 = []
roa4 = [
r
for r in roa4
if r["prefix"].prefixlen <= args.max or r["prefix"].prefixlen == max_prefixlen
]
roa6 = [r for r in roa6 if r["prefix"].prefixlen <= args.max6]
for r in roa4:
r["maxLength"] = args.max
if r["prefix"].prefixlen == max_prefixlen:
r["maxLength"] = max_prefixlen
for r in roa6:
r["maxLength"] = args.max6
for r in (*roa4, *roa6):
r["prefix"] = r["prefix"].with_prefixlen
return roa4, roa6
示例4: __init__
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Network [as 别名]
def __init__(self, value):
if not isinstance(
value,
(
ipaddress.IPv4Address,
ipaddress.IPv6Address,
ipaddress.IPv4Network,
ipaddress.IPv6Network
)
):
raise TypeError(
"value must be an instance of ipaddress.IPv4Address, "
"ipaddress.IPv6Address, ipaddress.IPv4Network, or "
"ipaddress.IPv6Network"
)
self._value = value
示例5: ips_fully_encompassed
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Network [as 别名]
def ips_fully_encompassed(lower_priority_cidr, higher_priority_cidr):
ledger = []
if lower_priority_cidr and not higher_priority_cidr:
return False
if higher_priority_cidr and not lower_priority_cidr:
return False
if not lower_priority_cidr and not higher_priority_cidr:
return True
for lower_cidr in lower_priority_cidr:
encompassed = False
for higher_cidr in higher_priority_cidr:
if IPv4Network(lower_cidr).subnet_of(IPv4Network(higher_cidr)):
encompassed = True
ledger.append(encompassed)
if False in ledger:
return False
else:
return True
示例6: active_network_addresses
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Network [as 别名]
def active_network_addresses(hypervisor):
"""Query libvirt for the already reserved addresses."""
active = []
for network in hypervisor.listNetworks():
try:
xml = hypervisor.networkLookupByName(network).XMLDesc(0)
except libvirt.libvirtError: # network has been destroyed meanwhile
continue
else:
ip_element = etree.fromstring(xml).find('.//ip')
address = ip_element.get('address')
netmask = ip_element.get('netmask')
active.append(ipaddress.IPv4Network(u'/'.join((address, netmask)),
strict=False))
return active
示例7: test_valid
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Network [as 别名]
def test_valid(self):
"""NETWORK A valid address is retrieved."""
virnetwork = mock.Mock()
hypervisor = mock.Mock()
virnetwork.XMLDesc.side_effect = (
lambda x:
'<a><ip address="192.168.%s.1" netmask="255.255.255.0"/></a>'
% random.randint(1, 255))
hypervisor.listNetworks.return_value = ('foo', 'bar', 'baz')
hypervisor.networkLookupByName.return_value = virnetwork
configuration = {'ipv4': '192.168.0.0',
'prefix': 16,
'subnet_prefix': 24}
self.assertTrue(network.generate_address(hypervisor, configuration) in
[ipaddress.IPv4Network(u'192.168.{}.0/24'.format(i))
for i in range(1, 255)])
示例8: gen_etc_hosts
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Network [as 别名]
def gen_etc_hosts(self, client, net):
"""Generate /etc/hosts file containing all subnet hosts
Makes it possible to register k8s nodes by hostname.
Disgusting hack to make up for OVH's terrible DNS.
"""
from ipaddress import IPv4Network
subnet = client.get('/cloud/project/{}/network/private/{}/subnet'.format(client._project, net))[0]
hosts = IPv4Network(subnet['cidr']).hosts()
hosts_content = ('127.0.0.1\tlocalhost\n' + '::1\t\tlocalhost\n' +
'\n'.join(['{}\t{}'.format(ip, 'host-'+str(ip).replace('.', '-')) for ip in hosts]) + '\n').encode()
self.add_files([
{
'filesystem': 'root',
'path': '/etc/hosts',
'mode': 420, # 0644
'contents': {
'source': 'data:,' + quote(hosts_content)
}
}
])
示例9: scan
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Network [as 别名]
def scan(self, netmask: str = None):
netmask = netmask or self.netmask
assert netmask, 'Scan not supported: No netmask specified'
workers = Workers(10, Scanner, port=self.port)
with workers:
for addr in ipaddress.IPv4Network(netmask):
workers.put(addr.exploded)
devices = {
dev.name: dev.addr
for dev in workers.responses
}
self._init_devices(devices)
return self.status()
# vim:sw=4:ts=4:et:
示例10: make_ipv4_prefix
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Network [as 别名]
def make_ipv4_prefix(prefix_str):
ipv4_network = ipaddress.IPv4Network(prefix_str)
address = int(ipv4_network.network_address)
prefixlen = ipv4_network.prefixlen
ipv4_prefix = common.ttypes.IPv4PrefixType(address, prefixlen)
prefix = common.ttypes.IPPrefixType(ipv4prefix=ipv4_prefix)
return prefix
示例11: ipv4_prefix_str
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Network [as 别名]
def ipv4_prefix_str(ipv4_prefix):
address = ipv4_prefix.address
length = ipv4_prefix.prefixlen
return str(ipaddress.IPv4Network((address, length)))
示例12: _is_ip_network
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Network [as 别名]
def _is_ip_network(value):
try:
ipaddress.IPv4Network(value)
return True
except (ValueError, ipaddress.AddressValueError):
pass
return False
示例13: _is_ip_rule_match
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Network [as 别名]
def _is_ip_rule_match(self, rule, fact):
if rule.match != '.*' and await self._is_ip_network(rule.match) and \
await self._is_ip_network(fact.value):
if ipaddress.IPv4Network(fact.value).subnet_of(ipaddress.IPv4Network(rule.match)):
return True
return False
示例14: finalize_args_and_env
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Network [as 别名]
def finalize_args_and_env(args, env):
global providers
# use the tunnel device as the VPN name if unspecified
if args.name is None:
args.name = env.tundev
# autodetect parent or grandparent process (skipping intermediary shell)
if args.ppid is None:
args.ppid = providers.process.ppid_of(None)
exe = providers.process.pid2exe(args.ppid)
if exe and os.path.basename(exe) in ('dash','bash','sh','tcsh','csh','ksh','zsh'):
args.ppid = providers.process.ppid_of(args.ppid)
# use the list from the env if --domain wasn't specified, but start with an
# empty list if it was specified; hence can't use 'default' here:
if args.domain is None:
args.domain = env.domain
args.subnets = []
args.exc_subnets = []
args.hosts = []
args.aliases = {}
for x in args.routes:
if isinstance(x, (IPv4Network, IPv6Network)):
args.subnets.append(x)
elif isinstance(x, str):
args.hosts.append(x)
else:
hosts, ip = x
args.aliases.setdefault(ip, []).extend(hosts)
if args.route_internal:
if env.network: args.subnets.append(env.network)
if env.network6: args.subnets.append(env.network6)
if args.route_splits:
args.subnets.extend(env.splitinc)
args.exc_subnets.extend(env.splitexc)
示例15: _check_if_private
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import IPv4Network [as 别名]
def _check_if_private(address: str, address_type: str) -> bool:
if address_type == "ipv6":
ip_list = [str(ip) for ip in IPv6Network(address)]
else:
ip_list = [str(ip) for ip in IPv4Network(address)]
if ip_address(ip_list[0]).is_private and ip_address(ip_list[-1]).is_private:
return True
return False