Python netaddr.IPAddress() Examples

The following are 30 code examples for showing how to use netaddr.IPAddress(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module netaddr , or try the search function .

Example 1
Project: JetPack   Author: dsp-jetpack   File: discover_nodes.py    License: Apache License 2.0 6 votes vote down vote up
def ip_address_from_address(address):
    try:
        ip_address = netaddr.IPAddress(address)
    except ValueError as e:
        # address contains a CIDR prefix, netmask, or hostmask.
        e.message = ('invalid IP address: %(address)s (detected CIDR, netmask,'
                     ' hostmask, or subnet)') % {'address': address}
        raise
    except netaddr.AddrFormatError as e:
        # address is not an IP address represented in an accepted string
        # format.
        e.message = ("invalid IP address: '%(address)s' (failed to detect a"
                     " valid IP address)") % {'address': address}
        raise

    if ip_address.version == 4:
        return ip_address
    else:
        raise NotSupported(
            ('invalid IP address: %(address)s (Internet Protocol version'
             ' %(version)s is not supported)') % {
                'address': address,
                'version': ip_address.version}) 
Example 2
Project: im   Author: grycap   File: vSphere.py    License: GNU General Public License v3.0 6 votes vote down vote up
def setIps(vm, node):
        """
        Set the IPs of the VM from the info obtained from vSphere
        """
        public_ips = []
        private_ips = []

        if node.guest:
            for nic in node.guest.net:
                if nic.ipAddress:
                    ip = nic.ipAddress
                    is_private = any([IPAddress(ip) in IPNetwork(mask) for mask in Config.PRIVATE_NET_MASKS])
                    if is_private:
                        private_ips.append(ip)
                    else:
                        public_ips.append(ip)

        vm.setIps(public_ips, private_ips) 
Example 3
Project: im   Author: grycap   File: OpenNebula.py    License: GNU General Public License v3.0 6 votes vote down vote up
def setIPsFromTemplate(vm, template):
        """
        Set the IPs of the VM from the info obtained in the ONE template object

        Arguments:
           - vm(:py:class:`IM.VirtualMachine`): VM information.
           - template(:py:class:`TEMPLATE`): ONE Template information.
        """
        system = vm.info.systems[0]
        for nic in template.NIC:
            i = 0
            while system.getValue("net_interface." + str(i) + ".connection"):
                net_name = system.getValue("net_interface." + str(i) + ".connection")
                net = vm.info.get_network_by_id(net_name)
                provider_id = net.getValue("provider_id")
                if provider_id == nic.NETWORK:
                    ip = str(nic.IP)
                    if IPAddress(ip).version == 6:
                        system.setValue("net_interface." + str(i) + ".ipv6", ip)
                    else:
                        system.setValue("net_interface." + str(i) + ".ip", ip)
                    break
                i += 1 
Example 4
Project: tempest-lib   Author: openstack   File: data_utils.py    License: Apache License 2.0 6 votes vote down vote up
def get_ipv6_addr_by_EUI64(cidr, mac):
    """Generate a IPv6 addr by EUI-64 with CIDR and MAC

    :param str cidr: a IPv6 CIDR
    :param str mac: a MAC address
    :return: an IPv6 Address
    :rtype: netaddr.IPAddress
    """
    # Check if the prefix is IPv4 address
    is_ipv4 = netaddr.valid_ipv4(cidr)
    if is_ipv4:
        msg = "Unable to generate IP address by EUI64 for IPv4 prefix"
        raise TypeError(msg)
    try:
        eui64 = int(netaddr.EUI(mac).eui64())
        prefix = netaddr.IPNetwork(cidr)
        return netaddr.IPAddress(prefix.first + eui64 ^ (1 << 57))
    except (ValueError, netaddr.AddrFormatError):
        raise TypeError('Bad prefix or mac format for generating IPv6 '
                        'address by EUI-64: %(prefix)s, %(mac)s:'
                        % {'prefix': cidr, 'mac': mac})
    except TypeError:
        raise TypeError('Bad prefix type for generate IPv6 address by '
                        'EUI-64: %s' % cidr) 
Example 5
Project: minemeld-core   Author: PaloAltoNetworks   File: ipop.py    License: Apache License 2.0 6 votes vote down vote up
def _range_from_indicator(self, indicator):
        if '-' in indicator:
            start, end = map(
                lambda x: int(netaddr.IPAddress(x)),
                indicator.split('-', 1)
            )
        elif '/' in indicator:
            ipnet = netaddr.IPNetwork(indicator)
            start = int(ipnet.ip)
            end = start+ipnet.size-1
        else:
            start = int(netaddr.IPAddress(indicator))
            end = start

        if (not (start >= 0 and start <= 0xFFFFFFFF)) or \
           (not (end >= 0 and end <= 0xFFFFFFFF)):
            LOG.error('%s - {%s} invalid IPv4 indicator',
                      self.name, indicator)
            return None, None

        return start, end 
Example 6
Project: minemeld-core   Author: PaloAltoNetworks   File: proofpoint.py    License: Apache License 2.0 6 votes vote down vote up
def _process_item(self, row):
        ipairs = super(EmergingThreatsIP, self)._process_item(row)

        result = []

        for i, v in ipairs:
            try:
                parsed_ip = netaddr.IPAddress(i)
            except:
                LOG.error('%s - invalid IP %s, ignored', self.name, i)
                continue

            if parsed_ip.version == 4:
                v['type'] = 'IPv4'
            elif parsed_ip.version == 6:
                v['type'] = 'IPv6'
            else:
                LOG.error('%s - unknown IP version %s, ignored', self.name, i)
                continue

            result.append([i, v])

        return result 
Example 7
Project: avocado-vt   Author: avocado-framework   File: test_setup.py    License: GNU General Public License v2.0 6 votes vote down vote up
def assign_static_ip(self):
        """
        Set the static IP for the PF devices for mlx5_core driver
        """
        # This function assigns static IP for the PF devices
        pf_devices = self.get_pf_ids()
        if (not self.start_addr_PF) or (not self.net_mask):
            raise exceptions.TestSetupFail(
                "No IP / netmask found, please populate starting IP address for PF devices in configuration file")
        ip_addr = netaddr.IPAddress(self.start_addr_PF)
        for PF in pf_devices:
            ifname = utils_misc.get_interface_from_pci_id(PF)
            ip_assign = "ifconfig %s %s netmask %s up" % (
                ifname, ip_addr, self.net_mask)
            logging.info("assign IP to PF device %s : %s", PF,
                         ip_assign)
            cmd = process.system(ip_assign, shell=True, ignore_status=True)
            if cmd:
                raise exceptions.TestSetupFail("Failed to assign IP : %s"
                                               % cmd)
            ip_addr += 1
        return True 
Example 8
Project: avocado-vt   Author: avocado-framework   File: utils_net.py    License: GNU General Public License v2.0 6 votes vote down vote up
def canonicalize(self, ip_str):
        """
        Parse an IP string for listen to IPAddress content.
        """
        try:
            if ':' in ip_str:
                self.version = 'ipv6'
                if '%' in ip_str:
                    ip_str, scope = ip_str.split('%')
                    self.scope = int(scope)
                self.packed_addr = socket.inet_pton(socket.AF_INET6, ip_str)
                self.addr = socket.inet_ntop(socket.AF_INET6, self.packed_addr)
            else:
                self.version = 'ipv4'
                self.packed_addr = socket.inet_pton(socket.AF_INET, ip_str)
                self.addr = socket.inet_ntop(socket.AF_INET, self.packed_addr)
        except socket.error as detail:
            if 'illegal IP address' in str(detail):
                self.addr = ip_str
                self.version = 'hostname' 
Example 9
Project: designate   Author: openstack   File: format.py    License: Apache License 2.0 6 votes vote down vote up
def is_ipv4(instance):
    if not isinstance(instance, compat.str_types):
        return True

    try:
        address = netaddr.IPAddress(instance, version=4)
        # netaddr happly accepts, and expands "127.0" into "127.0.0.0"
        if str(address) != instance:
            return False
    except Exception:
        return False

    if instance == '0.0.0.0':  # RFC5735
        return False

    return True 
Example 10
Project: privacyidea   Author: privacyidea   File: __init__.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def check_ip_in_policy(client_ip, policy):
    """
    This checks, if the given client IP is contained in a list like

       ["10.0.0.2", "192.168.2.1/24", "!192.168.2.12", "-172.16.200.1"]

    :param client_ip: The IP address in question
    :param policy: A string of single IP addresses, negated IP address and subnets.
    :return: tuple of (found, excluded)
    """
    client_found = False
    client_excluded = False
    # Remove empty strings from the list
    policy = list(filter(None, policy))
    for ipdef in policy:
        if ipdef[0] in ['-', '!']:
            # exclude the client?
            if IPAddress(client_ip) in IPNetwork(ipdef[1:]):
                log.debug(u"the client {0!s} is excluded by {1!s}".format(client_ip, ipdef))
                client_excluded = True
        elif IPAddress(client_ip) in IPNetwork(ipdef):
            client_found = True
    return client_found, client_excluded 
Example 11
Project: privacyidea   Author: privacyidea   File: machine.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def get_hostname(ip):
    """
    Return a hostname for a given IP address
    :param ip: IP address
    :type ip: IPAddress
    :return: hostname
    """
    machines = get_machines(ip=ip)
    if len(machines) > 1:
        raise Exception("Can not get unique ID for IP=%r. "
                        "More than one machine found." % ip)
    if len(machines) == 1:
        # There is only one machine in the list and we get its ID
        hostname = machines[0].hostname
        # return the first hostname
        if type(hostname) == list:
            hostname = hostname[0]
    else:
        raise Exception("There is no machine with IP={0!r}".format(ip))
    return hostname 
Example 12
Project: privacyidea   Author: privacyidea   File: base.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def has_ip(self, ip):
        """
        Checks if the machine has the given IP.
        A machine might have more than one IP Address. The ip is then
        provided as a list
        :param ip: The IP address to search for
        :type ip: Netaddr IPAddress
        :return: True or false
        """
        # convert to IPAddress
        if isinstance(ip, string_types):
            ip = netaddr.IPAddress(ip)

        if type(self.ip) == list:
            return ip in self.ip
        elif type(self.ip) == netaddr.IPAddress:
            return ip == self.ip 
Example 13
Project: privacyidea   Author: privacyidea   File: base.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def get_dict(self):
        """
        Convert the object attributes to a dict
        :return: dict of attributes
        """
        ip = self.ip
        if type(self.ip) == list:
            ip = ["{0!s}".format(i) for i in ip]
        elif type(self.ip) == netaddr.IPAddress:
            ip = "{0!s}".format(ip)

        d = {"hostname": self.hostname,
             "ip": ip,
             "resolver_name": self.resolver_name,
             "id": self.id}
        return d 
Example 14
Project: armory   Author: depthsecurity   File: Ingestor.py    License: GNU General Public License v3.0 6 votes vote down vote up
def process_ip(self, ip_str, force_scope=True):

        created, ip = self.IPAddress.find_or_create(
            only_tool=True,
            ip_address=ip_str,
            in_scope=self.in_scope,
            passive_scope=self.passive_scope,
        )
        if not created:
            if ip.in_scope != self.in_scope or ip.passive_scope != self.passive_scope:
                display(
                    "IP %s already exists with different scoping. Updating to Active Scope: %s Passive Scope: %s"
                    % (ip_str, self.in_scope, self.passive_scope)
                )

                ip.in_scope = self.in_scope
                ip.passive_scope = self.passive_scope
                ip.update()
        return ip 
Example 15
Project: armory   Author: depthsecurity   File: Ingestor.py    License: GNU General Public License v3.0 6 votes vote down vote up
def descope_ip(self, ip):
        ip = self.IPAddress.all(ip_address=ip)
        if ip:
            for i in ip:
                display("Removing IP {} from scope".format(i.ip_address))
                i.in_scope = False
                i.passive_scope = False
                i.update()
                for d in i.domains:
                    in_scope_ips = [
                        ipa
                        for ipa in d.ip_addresses
                        if ipa.in_scope or ipa.passive_scope
                    ]
                    if not in_scope_ips:
                        display(
                            "Domain {} has no more scoped IPs. Removing from scope.".format(
                                d.domain
                            )
                        )
                        d.in_scope = False
                        d.passive_scope = False
            self.IPAddress.commit() 
Example 16
Project: Hands-On-Enterprise-Automation-with-Python   Author: PacktPublishing   File: netaddr_module.py    License: MIT License 6 votes vote down vote up
def check_ip_address(ipaddr):
    ip_attributes = []
    ipaddress = IPAddress(ipaddr)

    if ipaddress.is_private():
        ip_attributes.append("IP Address is Private")

    else:
        ip_attributes.append("IP Address is public")

    if ipaddress.is_unicast():
        ip_attributes.append("IP Address is unicast")
    elif ipaddress.is_multicast():
        ip_attributes.append("IP Address is multicast")

    if ipaddress.is_loopback():
        ip_attributes.append("IP Address is loopback")

    return "\n".join(ip_attributes) 
Example 17
Project: iSDX   Author: sdn-ixp   File: arproxy.py    License: Apache License 2.0 5 votes vote down vote up
def start(self):
        while True:
            # receive arp requests
            packet, addr = self.sock.recvfrom(65565)
            eth_frame, arp_packet = parse_packet(packet)

            arp_type = struct.unpack("!h", arp_packet["oper"])[0]
            logger.debug("Received ARP-" + ("REQUEST" if (arp_type == 1) else "REPLY") +" SRC: "+eth_frame["src_mac"]+" / "+arp_packet["src_ip"]+" "+"DST: "+eth_frame["dst_mac"]+" / "+arp_packet["dst_ip"])

            if arp_type == 1:
                # check if the arp request stems from one of the participants
                requester_srcmac = eth_frame["src_mac"]
                requested_ip = arp_packet["dst_ip"]
                # Send the ARP request message to respective controller and forget about it
                if IPAddress(requested_ip) in config.vnhs:
                    self.send_arp_request(requester_srcmac, requested_ip)
    
                    # TODO: If the requested IP address belongs to a non-SDN participant
                    # then refer the structure `self.nonSDN_nhip_2_nhmac` and
                    # send an immediate ARP response.
                    """
                    response_vmac = self.get_vmac_default(requester_srcmac, requested_ip)
                    if response_vmac != "":
                        logger.debug("ARP-PROXY: reply with VMAC "+response_vmac)

                        data = self.craft_arp_packet(arp_packet, response_vmac)
                        eth_packet = self.craft_eth_frame(eth_frame, response_vmac, data)
                        self.sock.send(''.join(eth_packet))
                    """ 
Example 18
Project: BotDigger   Author: hanzhang0116   File: BotDigger.py    License: GNU General Public License v3.0 5 votes vote down vote up
def inPrefix(IP, networkPrefixDict):
	for prefix in networkPrefixDict:
		if IPAddress(IP) in IPNetwork(prefix):
			return 1
	return 0

# check whether a domain exists 
Example 19
Project: pulseaudio-dlna   Author: masmu   File: network.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __netaddr_get_host_by_ip(ip):
    import netaddr
    host = netaddr.IPAddress(ip)
    for iface in netifaces.interfaces():
        for link in netifaces.ifaddresses(iface).get(netifaces.AF_INET, []):
            addr = link.get('addr', None)
            netmask = link.get('netmask', None)
            if addr and netmask:
                if host in netaddr.IPNetwork('{}/{}'.format(addr, netmask)):
                    logger.debug(
                        'Selecting host "{}" for IP "{}"'.format(addr, ip))
                    return addr
    logger.critical(
        '__netaddr_get_host_by_ip - No host found for IP {}!'.format(ip))
    return None 
Example 20
Project: ec2-api   Author: openstack   File: network_interface.py    License: Apache License 2.0 5 votes vote down vote up
def assign_private_ip_addresses(context, network_interface_id,
                                private_ip_address=None,
                                secondary_private_ip_address_count=None,
                                allow_reassignment=False):
    # TODO(Alex): allow_reassignment is not supported at the moment
    network_interface = ec2utils.get_db_item(context, network_interface_id)
    subnet = db_api.get_item_by_id(context, network_interface['subnet_id'])
    neutron = clients.neutron(context)
    os_subnet = neutron.show_subnet(subnet['os_id'])['subnet']
    os_port = neutron.show_port(network_interface['os_id'])['port']
    subnet_ipnet = netaddr.IPNetwork(os_subnet['cidr'])
    fixed_ips = os_port['fixed_ips'] or []
    if private_ip_address is not None:
        for ip_address in private_ip_address:
            if netaddr.IPAddress(ip_address) not in subnet_ipnet:
                raise exception.InvalidParameterValue(
                    value=str(ip_address),
                    parameter='PrivateIpAddress',
                    reason='IP address is out of the subnet range')
            fixed_ips.append({'ip_address': str(ip_address)})
    elif secondary_private_ip_address_count > 0:
        for _i in range(secondary_private_ip_address_count):
            fixed_ips.append({'subnet_id': os_subnet['id']})
    try:
        neutron.update_port(os_port['id'],
                            {'port': {'fixed_ips': fixed_ips}})
    except neutron_exception.IpAddressGenerationFailureClient:
        raise exception.InsufficientFreeAddressesInSubnet()
    except neutron_exception.IpAddressInUseClient:
        msg = _('Some of %(addresses)s is assigned, but move is not '
                'allowed.') % {'addresses': private_ip_address}
        raise exception.InvalidParameterValue(msg)
    except neutron_exception.BadRequest as ex:
        # NOTE(ft):AWS returns PrivateIpAddressLimitExceeded, but Neutron does
        # general InvalidInput (converted to BadRequest) in the same case.
        msg = _('Specified network interface parameters are invalid. '
                'Reason: %(reason)s') % {'reason': ex.message}
        raise exception.InvalidParameterValue(msg)
    return True 
Example 21
Project: ec2-api   Author: openstack   File: dhcp_options.py    License: Apache License 2.0 5 votes vote down vote up
def create_dhcp_options(context, dhcp_configuration):
    dhcp_options = {}
    for dhcp_option in dhcp_configuration:
        key = dhcp_option['key']
        values = dhcp_option['value']
        if key not in DHCP_OPTIONS_MAP:
            raise exception.InvalidParameterValue(
                        value=values,
                        parameter=key,
                        reason='Unrecognized key is specified')
        if not type(values) is list:
            raise exception.InvalidParameterValue(
                value=values,
                parameter=key,
                reason='List of values is expected')
        if key not in ['domain-name', 'netbios-node-type']:
            ips = []
            for ip in values:
                ip_address = netaddr.IPAddress(ip)
                if not ip_address:
                    raise exception.InvalidParameterValue(
                        value=ip,
                        parameter=key,
                        reason='Invalid list of IPs is specified')
                ips.append(ip)
            dhcp_options[key] = ips
        else:
            dhcp_options[key] = values
    dhcp_options = db_api.add_item(context, 'dopt',
                                   {'dhcp_configuration': dhcp_options})
    return {'dhcpOptions': _format_dhcp_options(context, dhcp_options)} 
Example 22
Project: im   Author: grycap   File: vSphere.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_networks(content, datacenter):
        """
        Returns all metworks
        """
        nets = {}
        poolmgr = vim.IpPoolManager()
        ippools = poolmgr.QueryIpPools(datacenter)
        container = content.viewManager.CreateContainerView(content.rootFolder, [vim.Network], True)
        for c in container.view:
            is_public = None
            for ippool in ippools:
                if c.summary.ipPoolName == ippool.name:
                    is_public = not any([IPAddress(ippool.ipv4Config.subnetAddress) in IPNetwork(
                        mask) for mask in Config.PRIVATE_NET_MASKS])
                    break

            nets[c.name] = (c, is_public, ippool.ipv4Config)

        return nets 
Example 23
Project: im   Author: grycap   File: OCCI.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_net_info(occi_res):
        """
        Get the net related information about a VM from the OCCI information returned by the server
        """
        # Link:
        # </network/1>;rel="http://schemas.ogf.org/occi/infrastructure#network";self="/link/networkinterface/compute_10_nic_0";category="http://schemas.ogf.org/occi/infrastructure#networkinterface
        # http://schemas.ogf.org/occi/infrastructure/networkinterface#ipnetworkinterface
        # http://opennebula.org/occi/infrastructure#networkinterface";occi.core.id="compute_10_nic_0";occi.core.title="private";occi.core.target="/network/1";occi.core.source="/compute/10";occi.networkinterface.interface="eth0";occi.networkinterface.mac="10:00:00:00:00:05";occi.networkinterface.state="active";occi.networkinterface.address="10.100.1.5";org.opennebula.networkinterface.bridge="br1"
        lines = occi_res.split("\n")
        res = []
        link_to_public = False
        num_interface = None
        ip_address = None
        link = None
        for line in lines:
            if 'Link:' in line and '/network/public' in line:
                link_to_public = True
            if 'Link:' in line and ('/network/' in line or '/networklink/' in line):
                parts = line.split(';')
                for part in parts:
                    kv = part.split('=')
                    if kv[0].strip() == "occi.networkinterface.address":
                        if kv[1].count('.') == 3 or ip_address is None:
                            ip_address = kv[1].strip('"')
                            is_private = any([IPAddress(ip_address) in IPNetwork(
                                mask) for mask in Config.PRIVATE_NET_MASKS])
                    elif kv[0].strip() == "occi.networkinterface.interface":
                        net_interface = kv[1].strip('"')
                        num_interface = re.findall('\d+', net_interface)[0]
                    elif kv[0].strip() == "self":
                        link = kv[1].strip('"')
                if num_interface and ip_address:
                    res.append((num_interface, ip_address, not is_private, link))
        return link_to_public, res 
Example 24
Project: tempest-lib   Author: openstack   File: test_data_utils.py    License: Apache License 2.0 5 votes vote down vote up
def test_get_ipv6_addr_by_EUI64(self):
        actual = data_utils.get_ipv6_addr_by_EUI64('2001:db8::',
                                                   '00:16:3e:33:44:55')
        self.assertIsInstance(actual, netaddr.IPAddress)
        self.assertEqual(actual,
                         netaddr.IPAddress('2001:db8::216:3eff:fe33:4455')) 
Example 25
Project: lsassy   Author: Hackndo   File: utils.py    License: MIT License 5 votes vote down vote up
def parse_targets(target):
    if '-' in target:
        ip_range = target.split('-')
        try:
            t = IPRange(ip_range[0], ip_range[1])
        except AddrFormatError:
            try:
                start_ip = IPAddress(ip_range[0])

                start_ip_words = list(start_ip.words)
                start_ip_words[-1] = ip_range[1]
                start_ip_words = [str(v) for v in start_ip_words]

                end_ip = IPAddress('.'.join(start_ip_words))

                t = IPRange(start_ip, end_ip)
            except AddrFormatError:
                t = target
    else:
        try:
            t = IPNetwork(target)
        except AddrFormatError:
            t = target
    if type(t) == IPNetwork or type(t) == IPRange:
        return list(t)
    else:
        return [t.strip()] 
Example 26
Project: lanscan   Author: sumpfgottheit   File: lanscan.py    License: MIT License 5 votes vote down vote up
def __init__(self, ip_address, mac_address):
        self.ip = ip_address
        self.mac = mac_address
        self.sort_value = netaddr.IPAddress(self.ip).value
        try:
            self.hostname = socket.gethostbyaddr(self.ip)[0]
        except socket.herror:
            # failed to resolve
            self.hostname = ''
        self.vendor = ''
        self.is_alive = False
        self.open_ports = {} 
Example 27
Project: lanscan   Author: sumpfgottheit   File: lanscan.py    License: MIT License 5 votes vote down vote up
def __init__(self, interface_name, network_ip, netmask, prefix, driver, hardware, is_default_network):
        self.interface_name = interface_name
        self.network_ip = network_ip
        self.netmask = netmask
        self.prefix = prefix
        self.driver = driver
        self.hardware = hardware
        self.is_default_network = is_default_network
        self.sort_value = netaddr.IPAddress(self.network_ip).value
        self.netaddr_ip = netaddr.IPNetwork("{}/{}".format(self.network_ip, self.netmask))
        self.neighbours = [] 
Example 28
Project: minemeld-core   Author: PaloAltoNetworks   File: test.py    License: Apache License 2.0 5 votes vote down vote up
def _run(self):
        cip = 0x0A000000

        v = {
            'type': 'IPv4',
            'confidence': 0,
            'share_level': 'red'
        }

        LOG.info('%s - start sending messages: %d', self.name, utc_millisec())

        t1 = utc_millisec()
        for i in xrange(self.num_messages):
            ip = str(netaddr.IPAddress(i+cip))
            self.emit_update(ip, v)

            if ((i+1) % self.mps) == 0:
                now = utc_millisec()
                LOG.info('%d: %d', i+1, now - t1)

                if now - t1 < 1000:
                    gevent.sleep((1000 - now + t1)/1000.0)

                t1 = now

        LOG.info('%s - all messages sent: %d', self.name, utc_millisec()) 
Example 29
Project: minemeld-core   Author: PaloAltoNetworks   File: ipop.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, start, end, uuids):
        self.start = start
        self.end = end
        self.uuids = set(uuids)

        s = netaddr.IPAddress(start)
        e = netaddr.IPAddress(end)
        self._indicator = '%s-%s' % (s, e) 
Example 30
Project: minemeld-core   Author: PaloAltoNetworks   File: ipop.py    License: Apache License 2.0 5 votes vote down vote up
def get_range(self, source=None, index=None, from_key=None, to_key=None):
        if index is not None:
            raise ValueError('Index not found')
        if from_key is not None:
            from_key = int(netaddr.IPAddress(from_key))
        if to_key is not None:
            to_key = int(netaddr.IPAddress(to_key))

        self._send_indicators(
            source=source,
            from_key=from_key,
            to_key=to_key
        )

        return 'OK'