Iterate over ip info and extract useful data
438743
def _process_cidr_file(self, file):
        
        data = {'cidr': list(), 'countries': set(), 'city_country_mapping': dict()}
        allowed_countries = settings.IPGEOBASE_ALLOWED_COUNTRIES
        for cidr_info in self._line_to_dict(file, field_names=settings.IPGEOBASE_CIDR_FIELDS):
            city_id = cidr_info['city_id'] if cidr_info['city_id'] != '-' else None
            if city_id is not None:
                data['city_country_mapping'].update({cidr_info['city_id']: cidr_info['country_code']})

            if allowed_countries and cidr_info['country_code'] not in allowed_countries:
                continue
            data['cidr'].append({'start_ip': cidr_info['start_ip'],
                                 'end_ip': cidr_info['end_ip'],
                                 'country_id': cidr_info['country_code'],
                                 'city_id': city_id})
            data['countries'].add(cidr_info['country_code'])
        return data
468183
def ipinfo_ip_check(ip):
    """"""
    if not is_IPv4Address(ip):
        return None

    response = requests.get('http://ipinfo.io/%s/json' % ip)
    return response.json()
1190958
def list_cidr_ips(cidr):
    '''
    
    '''
    ips = netaddr.IPNetwork(cidr)
    return [six.text_type(ip) for ip in list(ips)]
604995
def get(self):
        """"""
        q = queue.Queue()

        for u, j, k in urls:
            t = threading.Thread(target=self._get_ip_public, args=(q, u, j, k))
            t.daemon = True
            t.start()

        timer = Timer(self.timeout)
        ip = None
        while not timer.finished() and ip is None:
            if q.qsize() > 0:
                ip = q.get()

        return ', '.join(set([x.strip() for x in ip.split(',')]))
335046
def _analyze(self):
        
        for parsed_line in self.parsed_lines:
            if 'ip' in parsed_line:
                if parsed_line['ip'] in self.filter['ips']:
                    self.noisy_logs.append(parsed_line)
                else:
                    self.quiet_logs.append(parsed_line)
            else:
                self.quiet_logs.append(parsed_line)
993589
def cli(env, ip_address):
    """"""

    mgr = SoftLayer.NetworkManager(env.client)

    addr_info = mgr.ip_lookup(ip_address)

    if not addr_info:
        raise exceptions.CLIAbort('Not found')

    table = formatting.KeyValueTable(['name', 'value'])
    table.align['name'] = 'r'
    table.align['value'] = 'l'

    table.add_row(['id', addr_info['id']])
    table.add_row(['ip', addr_info['ipAddress']])

    subnet_table = formatting.KeyValueTable(['name', 'value'])
    subnet_table.align['name'] = 'r'
    subnet_table.align['value'] = 'l'
    subnet_table.add_row(['id', addr_info['subnet']['id']])
    subnet_table.add_row(['identifier',
                          '%s/%s' % (addr_info['subnet']['networkIdentifier'],
                                     str(addr_info['subnet']['cidr']))])
    subnet_table.add_row(['netmask', addr_info['subnet']['netmask']])
    if addr_info['subnet'].get('gateway'):
        subnet_table.add_row(['gateway', addr_info['subnet']['gateway']])
    subnet_table.add_row(['type', addr_info['subnet'].get('subnetType')])

    table.add_row(['subnet', subnet_table])

    if addr_info.get('virtualGuest') or addr_info.get('hardware'):
        device_table = formatting.KeyValueTable(['name', 'value'])
        device_table.align['name'] = 'r'
        device_table.align['value'] = 'l'
        if addr_info.get('virtualGuest'):
            device = addr_info['virtualGuest']
            device_type = 'vs'
        else:
            device = addr_info['hardware']
            device_type = 'server'
        device_table.add_row(['id', device['id']])
        device_table.add_row(['name', device['fullyQualifiedDomainName']])
        device_table.add_row(['type', device_type])
        table.add_row(['device', device_table])
    env.fout(table)
480934
def get_ips(linode_id=None):
    '''
    
    '''
    if linode_id:
        ips = _query('linode', 'ip.list', args={'LinodeID': linode_id})
    else:
        ips = _query('linode', 'ip.list')

    ips = ips['DATA']
    ret = {}

    for item in ips:
        node_id = six.text_type(item['LINODEID'])
        if item['ISPUBLIC'] == 1:
            key = 'public_ips'
        else:
            key = 'private_ips'

        if ret.get(node_id) is None:
            ret.update({node_id: {'public_ips': [], 'private_ips': []}})
        ret[node_id][key].append(item['IPADDRESS'])

    # If linode_id was specified, only return the ips, and not the
    # dictionary based on the linode ID as a key.
    if linode_id:
        _all_ips = {'public_ips': [], 'private_ips': []}
        matching_id = ret.get(six.text_type(linode_id))
        if matching_id:
            _all_ips['private_ips'] = matching_id['private_ips']
            _all_ips['public_ips'] = matching_id['public_ips']

        ret = _all_ips

    return ret
540039
def ip_info(self, ip, repository_ids=None):
        
        if not repository_ids:
            repository_ids = []
        repos = []
        for rid in repository_ids:
            repos.append({'id': rid})
        return self.raw_query('vuln', 'getIP', data={
            'ip': ip, 'repositories': repos})
269565
def _analyze(self):
        
        pids = []

        for ip in self.filter['ips']:
            if ip in self.ips_to_pids:
                for pid in self.ips_to_pids[ip]:
                    pids.append(pid)

        for line in self.parsed_lines:
            if 'processid' in line and line['processid'] in pids:
                self.noisy_logs.append(line)
            else:
                self.quiet_logs.append(line)
130139
def lookup(self, ip_address):
        """"""

        # Is this already in our cache
        if self.ip_lookup_cache.get(ip_address):
            domain = self.ip_lookup_cache.get(ip_address)

        # Is the ip_address local or special
        elif not self.lookup_internal and net_utils.is_internal(ip_address):
            domain = 'internal'
        elif net_utils.is_special(ip_address):
            domain = net_utils.is_special(ip_address)

        # Look it up at this point
        else:
            domain = self._reverse_dns_lookup(ip_address)

        # Cache it
        self.ip_lookup_cache.set(ip_address, domain)

        # Return the domain
        return domain
1013514
def RetrieveIP4Info(self, ip):
    """"""
    if ip.is_private:
      return (IPInfo.INTERNAL, "Internal IP address.")
    try:
      # It's an external IP, let's try to do a reverse lookup.
      res = socket.getnameinfo((str(ip), 0), socket.NI_NAMEREQD)
      return (IPInfo.EXTERNAL, res[0])
    except (socket.error, socket.herror, socket.gaierror):
      return (IPInfo.EXTERNAL, "Unknown IP address.")
688855
def _find_interfaces_mac(ip):  # pylint: disable=invalid-name
    '''
    
    '''
    all_interfaces = _get_mine('net.interfaces')
    all_ipaddrs = _get_mine('net.ipaddrs')

    for device, device_ipaddrs in six.iteritems(all_ipaddrs):
        if not device_ipaddrs.get('result', False):
            continue
        for interface, interface_ipaddrs in six.iteritems(device_ipaddrs.get('out', {})):
            ip_addresses = interface_ipaddrs.get('ipv4', {}).keys()
            ip_addresses.extend(interface_ipaddrs.get('ipv6', {}).keys())
            for ipaddr in ip_addresses:
                if ip != ipaddr:
                    continue
                interface_mac = all_interfaces.get(device, {}).get('out', {}).get(interface, {}).get('mac_address', '')
                return device, interface, interface_mac

    return ('', '', '')
276064
def from_ip(cls, ip):
        """"""
        ips = dict([(ip_['ip'], ip_['id'])
                    for ip_ in cls.list({'items_per_page': 500})])
        return ips.get(ip)
485530
def list_network_ip_availabilities(self, retrieve_all=True, **_params):
        """"""
        return self.list('network_ip_availabilities',
                         self.network_ip_availabilities_path,
                         retrieve_all, **_params)
381508
def as_for_ip(self, ip):
        ''''''
        if not Investigate.IP_PATTERN.match(ip):
            raise Investigate.IP_ERR

        uri = self._uris["as_for_ip"].format(ip)
        resp_json = self.get_parse(uri)

        return resp_json
1200901
def _convert_addrinfo(cls, results: List[tuple]) -> Iterable[AddressInfo]:
        ''''''
        for result in results:
            family = result[0]
            address = result[4]
            ip_address = address[0]

            if family == socket.AF_INET6:
                flow_info = address[2]
                control_id = address[3]
            else:
                flow_info = None
                control_id = None

            yield AddressInfo(ip_address, family, flow_info, control_id)
1001353
def get_ip_address(request):
    
    if 'HTTP_X_FORWARDED_FOR' in request.META:
        return request.META['HTTP_X_FORWARDED_FOR'].split(',')[0].strip()
    else:
        return request.META['REMOTE_ADDR']