def get_subnets(network, min_length=None): """Retrieves all the subnets of the argument ``network''. Arguments: ``min_length'': minimum subnet mask length, defaults to network.prefixlen(). Returns: List with IPy.IP objects """ max_length = 128 if network.version() == 6 else 32 if min_length is None: min_length = network.prefixlen() assert min_length < max_length sql = """ SELECT netaddr FROM prefix WHERE family(netaddr)=%s AND netaddr << %s AND masklen(netaddr) >= %s AND masklen(netaddr) < %s """ args = (network.version(), str(network), min_length, max_length) db_cursor = db.getConnection('default').cursor() db_cursor.execute(sql.strip(), args) db_result = db_cursor.fetchall() return [IP(i[0]) for i in db_result]
def validate(self, data): try: if IP(data['prefix']).version() == 4 and data['prefixlen'] > 32: raise serializers.ValidationError( "Prefixlen can not be higher than 32 for ipv4 prefixes") except ValueError: raise serializers.ValidationError("Invalid prefix") return data
def __new__(cls, *args, **_kwargs): arg = args[0] if arg and isinstance(arg, six.binary_type): addr_type = arg[0] addr_string = arg[1:] if addr_type in cls.ADDR_FAMILY: try: ipstring = socket.inet_ntop(cls.ADDR_FAMILY[addr_type], addr_string) arg = IP(ipstring) except (socket.error, ValueError): pass elif arg and isinstance(arg, cls): return arg return IdType.__new__(cls, arg)
def usage(self, request, *args, **kwargs): "Return usage for Prefix.pk == pk" pk = kwargs.pop("pk", None) prefix = Prefix.objects.get(pk=pk) max_addr = IP(prefix.net_address).len() active_addr = prefix_collector.collect_active_ip(prefix) # calculate allocated ratio query = PrefixQuerysetBuilder().within(prefix.net_address) allocated = query.finalize().exclude(vlan__net_type="scope") total_allocated = sum(p.get_prefix_size() for p in allocated) payload = { "max_addr": max_addr, "active_addr": active_addr, "usage": 1.0 * active_addr / max_addr, "allocated": 1.0 * total_allocated / max_addr, "pk": pk, } return Response(payload, status=status.HTTP_200_OK)
def _make_cache_tuple(index, row): if row['cdpCacheAddressType'] != ADDRESS_TYPE_IP: return ifindex, _deviceindex = index if row['cdpCacheAddress']: try: ipstring = socket.inet_ntoa(row['cdpCacheAddress']) ip = IP(ipstring) except (socket.error, ValueError): ip = None else: ip = None deviceid = row['cdpCacheDeviceId'] or None deviceport = row['cdpCacheDevicePort'] or None if not (ip or deviceid): # we have no idea how to identify this record, ignore it return return CDPNeighbor(ifindex, ip, deviceid, deviceport)