Python ipaddress.IPv4Network() Examples
The following are 30
code examples of ipaddress.IPv4Network().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
ipaddress
, or try the search function
.
Example #1
Source File: userdata.py From kOVHernetes with Apache License 2.0 | 6 votes |
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) } } ])
Example #2
Source File: general_name.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
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
Example #3
Source File: general_name.py From teleport with Apache License 2.0 | 6 votes |
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
Example #4
Source File: general_name.py From learn_python3_spider with MIT License | 6 votes |
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
Example #5
Source File: nx.py From nxBender with BSD 3-Clause "New" or "Revised" License | 6 votes |
def setup_routes(self, gateway): ip = pyroute2.IPRoute() for route in set(self.routes): net = ipaddress.IPv4Network(unicode(route)) dst = '%s/%d' % (net.network_address, net.prefixlen) ip.route("add", dst=dst, gateway=gateway) logging.info("Remote routing configured, VPN is up")
Example #6
Source File: general_name.py From teleport with Apache License 2.0 | 6 votes |
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
Example #7
Source File: general_name.py From oss-ftp with MIT License | 6 votes |
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
Example #8
Source File: roa.py From NeoNetwork with The Unlicense | 6 votes |
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
Example #9
Source File: firewalls.py From G-Scout with GNU General Public License v3.0 | 6 votes |
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
Example #10
Source File: create_securitygroup.py From foremast with Apache License 2.0 | 6 votes |
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
Example #11
Source File: network_test.py From see with Apache License 2.0 | 6 votes |
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)])
Example #12
Source File: nat.py From pyquarkchain with MIT License | 6 votes |
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)
Example #13
Source File: network.py From see with Apache License 2.0 | 6 votes |
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
Example #14
Source File: __init__.py From platypush with MIT License | 6 votes |
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:
Example #15
Source File: test_ipaddress.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def testInternals(self): ip1 = ipaddress.IPv4Address('10.10.10.10') ip2 = ipaddress.IPv4Address('10.10.10.11') ip3 = ipaddress.IPv4Address('10.10.10.12') self.assertEqual(list(ipaddress._find_address_range([ip1])), [(ip1, ip1)]) self.assertEqual(list(ipaddress._find_address_range([ip1, ip3])), [(ip1, ip1), (ip3, ip3)]) self.assertEqual(list(ipaddress._find_address_range([ip1, ip2, ip3])), [(ip1, ip3)]) self.assertEqual(128, ipaddress._count_righthand_zero_bits(0, 128)) self.assertEqual("IPv4Network('1.2.3.0/24')", repr(self.ipv4_network))
Example #16
Source File: test_ipaddress.py From ironpython3 with Apache License 2.0 | 5 votes |
def testIPv4NetAndHostmasks(self): net = self.ipv4_network self.assertFalse(net._is_valid_netmask('invalid')) self.assertTrue(net._is_valid_netmask('128.128.128.128')) self.assertFalse(net._is_valid_netmask('128.128.128.127')) self.assertFalse(net._is_valid_netmask('128.128.128.255')) self.assertTrue(net._is_valid_netmask('255.128.128.128')) self.assertFalse(net._is_hostmask('invalid')) self.assertTrue(net._is_hostmask('128.255.255.255')) self.assertFalse(net._is_hostmask('255.255.255.255')) self.assertFalse(net._is_hostmask('1.2.3.4')) net = ipaddress.IPv4Network('127.0.0.0/0.0.0.255') self.assertEqual(net.prefixlen, 24)
Example #17
Source File: test_ipaddress.py From ironpython3 with Apache License 2.0 | 5 votes |
def testOverlaps(self): other = ipaddress.IPv4Network('1.2.3.0/30') other2 = ipaddress.IPv4Network('1.2.2.0/24') other3 = ipaddress.IPv4Network('1.2.2.64/26') self.assertTrue(self.ipv4_network.overlaps(other)) self.assertFalse(self.ipv4_network.overlaps(other2)) self.assertTrue(other2.overlaps(other3))
Example #18
Source File: test_ipaddress.py From ironpython3 with Apache License 2.0 | 5 votes |
def testGetSubnetForSingle32(self): ip = ipaddress.IPv4Network('1.2.3.4/32') subnets1 = [str(x) for x in ip.subnets()] subnets2 = [str(x) for x in ip.subnets(2)] self.assertEqual(subnets1, ['1.2.3.4/32']) self.assertEqual(subnets1, subnets2)
Example #19
Source File: test_ipaddress.py From ironpython3 with Apache License 2.0 | 5 votes |
def testGetitem(self): # http://code.google.com/p/ipaddr-py/issues/detail?id=15 addr = ipaddress.IPv4Network('172.31.255.128/255.255.255.240') self.assertEqual(28, addr.prefixlen) addr_list = list(addr) self.assertEqual('172.31.255.128', str(addr_list[0])) self.assertEqual('172.31.255.128', str(addr[0])) self.assertEqual('172.31.255.143', str(addr_list[-1])) self.assertEqual('172.31.255.143', str(addr[-1])) self.assertEqual(addr_list[-1], addr[-1])
Example #20
Source File: test_ipaddress.py From ironpython3 with Apache License 2.0 | 5 votes |
def testGetSupernet(self): self.assertEqual(self.ipv4_network.supernet().prefixlen, 23) self.assertEqual(str(self.ipv4_network.supernet().network_address), '1.2.2.0') self.assertEqual( ipaddress.IPv4Interface('0.0.0.0/0').network.supernet(), ipaddress.IPv4Network('0.0.0.0/0')) self.assertEqual(self.ipv6_network.supernet().prefixlen, 63) self.assertEqual(str(self.ipv6_network.supernet().network_address), '2001:658:22a:cafe::') self.assertEqual(ipaddress.IPv6Interface('::0/0').network.supernet(), ipaddress.IPv6Network('::0/0'))
Example #21
Source File: fields.py From lemur with Apache License 2.0 | 5 votes |
def _serialize(self, value, attr, obj): general_names = [] name_type = None if value: for name in value._general_names: value = name.value if isinstance(name, x509.DNSName): name_type = "DNSName" elif isinstance(name, x509.IPAddress): if isinstance(value, ipaddress.IPv4Network): name_type = "IPNetwork" else: name_type = "IPAddress" value = str(value) elif isinstance(name, x509.UniformResourceIdentifier): name_type = "uniformResourceIdentifier" elif isinstance(name, x509.DirectoryName): name_type = "directoryName" elif isinstance(name, x509.RFC822Name): name_type = "rfc822Name" elif isinstance(name, x509.RegisteredID): name_type = "registeredID" value = value.dotted_string else: current_app.logger.warning( "Unknown SubAltName type: {name}".format(name=name) ) continue general_names.append({"nameType": name_type, "value": value}) return general_names
Example #22
Source File: test_ipaddress.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def setUp(self): self.ipv4_address = ipaddress.IPv4Address('1.2.3.4') self.ipv4_interface = ipaddress.IPv4Interface('1.2.3.4/24') self.ipv4_network = ipaddress.IPv4Network('1.2.3.0/24') #self.ipv4_hostmask = ipaddress.IPv4Interface('10.0.0.1/0.255.255.255') self.ipv6_address = ipaddress.IPv6Interface( '2001:658:22a:cafe:200:0:0:1') self.ipv6_interface = ipaddress.IPv6Interface( '2001:658:22a:cafe:200:0:0:1/64') self.ipv6_network = ipaddress.IPv6Network('2001:658:22a:cafe::/64')
Example #23
Source File: test_ipaddress.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def testRepr(self): self.assertEqual("IPv4Interface('1.2.3.4/32')", repr(ipaddress.IPv4Interface('1.2.3.4'))) self.assertEqual("IPv6Interface('::1/128')", repr(ipaddress.IPv6Interface('::1'))) # issue #16531: constructing IPv4Network from a (address, mask) tuple
Example #24
Source File: test_ipaddress.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def testIPv4NetAndHostmasks(self): net = self.ipv4_network self.assertFalse(net._is_valid_netmask('invalid')) self.assertTrue(net._is_valid_netmask('128.128.128.128')) self.assertFalse(net._is_valid_netmask('128.128.128.127')) self.assertFalse(net._is_valid_netmask('128.128.128.255')) self.assertTrue(net._is_valid_netmask('255.128.128.128')) self.assertFalse(net._is_hostmask('invalid')) self.assertTrue(net._is_hostmask('128.255.255.255')) self.assertFalse(net._is_hostmask('255.255.255.255')) self.assertFalse(net._is_hostmask('1.2.3.4')) net = ipaddress.IPv4Network('127.0.0.0/0.0.0.255') self.assertEqual(net.prefixlen, 24)
Example #25
Source File: ping_ip.py From snippet with MIT License | 5 votes |
def parse_ips(args): ips = set() for v in args: for ip in v.split(","): ip = ip.strip() if not ip: continue if "/" not in ip: ips.add(ip) continue for ip in ipaddress.IPv4Network(ip, strict=False).hosts(): ips.add(str(ip)) return sorted(ips)
Example #26
Source File: test_ipaddress.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def testIpType(self): ipv4net = ipaddress.ip_network('1.2.3.4') ipv4addr = ipaddress.ip_address('1.2.3.4') ipv6net = ipaddress.ip_network('::1.2.3.4') ipv6addr = ipaddress.ip_address('::1.2.3.4') self.assertEqual(ipaddress.IPv4Network, type(ipv4net)) self.assertEqual(ipaddress.IPv4Address, type(ipv4addr)) self.assertEqual(ipaddress.IPv6Network, type(ipv6net)) self.assertEqual(ipaddress.IPv6Address, type(ipv6addr))
Example #27
Source File: test_ipaddress.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def testOverlaps(self): other = ipaddress.IPv4Network('1.2.3.0/30') other2 = ipaddress.IPv4Network('1.2.2.0/24') other3 = ipaddress.IPv4Network('1.2.2.64/26') self.assertTrue(self.ipv4_network.overlaps(other)) self.assertFalse(self.ipv4_network.overlaps(other2)) self.assertTrue(other2.overlaps(other3))
Example #28
Source File: test_ipaddress.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def testGetSupernet(self): self.assertEqual(self.ipv4_network.supernet().prefixlen, 23) self.assertEqual(str(self.ipv4_network.supernet().network_address), '1.2.2.0') self.assertEqual( ipaddress.IPv4Interface('0.0.0.0/0').network.supernet(), ipaddress.IPv4Network('0.0.0.0/0')) self.assertEqual(self.ipv6_network.supernet().prefixlen, 63) self.assertEqual(str(self.ipv6_network.supernet().network_address), '2001:658:22a:cafe::') self.assertEqual(ipaddress.IPv6Interface('::0/0').network.supernet(), ipaddress.IPv6Network('::0/0'))
Example #29
Source File: test_ipaddress.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def testGetitem(self): # http://code.google.com/p/ipaddr-py/issues/detail?id=15 addr = ipaddress.IPv4Network('172.31.255.128/255.255.255.240') self.assertEqual(28, addr.prefixlen) addr_list = list(addr) self.assertEqual('172.31.255.128', str(addr_list[0])) self.assertEqual('172.31.255.128', str(addr[0])) self.assertEqual('172.31.255.143', str(addr_list[-1])) self.assertEqual('172.31.255.143', str(addr[-1])) self.assertEqual(addr_list[-1], addr[-1])
Example #30
Source File: test_ipaddress.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def testContains(self): self.assertIn(ipaddress.IPv4Interface('1.2.3.128/25'), self.ipv4_network) self.assertNotIn(ipaddress.IPv4Interface('1.2.4.1/24'), self.ipv4_network) # We can test addresses and string as well. addr1 = ipaddress.IPv4Address('1.2.3.37') self.assertIn(addr1, self.ipv4_network) # issue 61, bad network comparison on like-ip'd network objects # with identical broadcast addresses. self.assertFalse(ipaddress.IPv4Network('1.1.0.0/16').__contains__( ipaddress.IPv4Network('1.0.0.0/15')))