If an IP Address is found, scan it
492610
def scan_ipaddr(ipaddr, line, project, split_path, apikey):
    
    logger.info('Found what I believe is an IP Address: %s', line.strip())
    logger.info('File %s. Parsed IP Address: %s', split_path, ipaddr)
    with open(reports_dir + "ips-" + project + ".log", "a") as gate_report:
        gate_report.write('File {} contains what I believe is an IP Address: {}\n'.format(split_path, ipaddr))
    v_api = virus_total.VirusTotal()
    scan_ip = v_api.send_ip(ipaddr, apikey)
    response_code = scan_ip['response_code']
    verbose_msg = scan_ip['verbose_msg']
    urls = scan_ip['detected_urls']
    with open(reports_dir + "ips-" + project + ".log", "a") as gate_report:
        if urls:
            logger.error('%s has been known to resolve to the following malicious urls:', ipaddr)
            gate_report.write('{} has been known to resolve to the following malicious urls:\n'.format(ipaddr))

            for url in urls:
                logger.info('%s on date: %s', url['url'], url['scan_date'])
                gate_report.write('{} on {}\n'.format(url['url'], url['scan_date']))
                sleep(0.2)
        else:
            logger.info('No malicious DNS history found for: %s', ipaddr)
            gate_report.write('No malicious DNS history found for: {}\n'.format(ipaddr))
597085
def _parse_ip(addr):
    

    # Parse the IP address
    try:
        address = netaddr.IPAddress(addr.strip())
    except (ValueError, netaddr.AddrFormatError):
        return None

    # Canonicalize it, if possible
    if address.version == 6:
        try:
            return address.ipv4()
        except netaddr.AddrConversionError:
            pass

    return address
241376
def find_ip_address(ipa_id=None, ipa_fqdn=None, ipa_ip_address=None, ipa_subnet_id=None, ipa_osi_id=None):
        
        LOGGER.debug("IPAddressService.find_ip_address")
        if (ipa_id is None or not ipa_id) and (ipa_fqdn is None or not ipa_fqdn) and \
                ((ipa_ip_address is None or not ipa_ip_address) and
                    ((ipa_subnet_id is None or not ipa_subnet_id) or (ipa_osi_id is None or not ipa_osi_id))):
            raise exceptions.ArianeCallParametersError('id and fqdn and (ip_address,(ip_subnet_id|ip_osi_id))')

        if (ipa_id is not None and ipa_id) and \
           ((ipa_fqdn is not None and ipa_fqdn) or (ipa_ip_address is not None and ipa_ip_address)):
            LOGGER.warn('IPAddressService.find_ip_address - Both id and (fqdn or ipAddress) are defined. '
                        'Will give you search on id.')
            ipa_fqdn = None
            ipa_ip_address = None
            ipa_osi_id = None
            ipa_subnet_id = None

        if (ipa_id is None or not ipa_id) and (ipa_fqdn is not None and ipa_fqdn) and \
                (ipa_ip_address is not None and ipa_ip_address):
            LOGGER.warn('IPAddressService.find_ip_address - Both fqdn and ipAddress are defined. '
                        'Will give you search on fqdn.')
            ipa_ip_address = None
            ipa_osi_id = None
            ipa_subnet_id = None

        params = None
        if ipa_id is not None and ipa_id:
            params = {'id': ipa_id}
        elif ipa_fqdn is not None and ipa_fqdn:
            params = {'fqdn': ipa_fqdn}
        elif (ipa_ip_address is not None and ipa_ip_address) and (ipa_subnet_id is not None and ipa_subnet_id):
            params = {'ipAddress': ipa_ip_address, 'subnetID': ipa_subnet_id}
        elif (ipa_ip_address is not None and ipa_ip_address) and (ipa_osi_id is not None and ipa_osi_id):
            params = {'ipAddress': ipa_ip_address, 'osiID': ipa_osi_id}

        ret = None
        if params is not None:
            args = {'http_operation': 'GET', 'operation_path': 'get', 'parameters': params}
            response = IPAddressService.requester.call(args)
            if response.rc == 0:
                ret = IPAddress.json_2_ip_address(response.response_content)
            elif response.rc != 404:
                err_msg = 'IPAddressService.find_ip_address - Problem while finding IP Address (id:' + \
                          str(ipa_id) + ', ipAddress:' + str(ipa_ip_address) \
                          + '). Reason: ' + str(response.response_content) + '-' + str(response.error_message) + \
                          " (" + str(response.rc) + ")"
                LOGGER.warning(
                    err_msg
                )

        return ret
1034142
async def scan(self, timeout=1):
        """"""
        adapters = await self.loop.run_in_executor(None, ifaddr.get_adapters)
        ips = [ip.ip for adapter in ifaddr.get_adapters() for ip in adapter.ips if ip.is_IPv4]

        if not ips:
            return []

        tasks = []
        discoveries = []
        for ip in ips:
            manager = ScanManager(ip)
            lifx_discovery = LifxDiscovery(self.loop, manager)
            discoveries.append(lifx_discovery)
            lifx_discovery.start(listen_ip=ip)
            tasks.append(self.loop.create_task(manager.lifx_ip()))

        (done, pending) = await aio.wait(tasks, timeout=timeout)

        for discovery in discoveries:
            discovery.cleanup()

        for task in pending:
            task.cancel()

        return [task.result() for task in done]
1315402
def get_ip(host):
    '''
    
    '''
    hosts = _list_hosts()
    if not hosts:
        return ''
    # Look for the op
    for addr in hosts:
        if host in hosts[addr]:
            return addr
    # ip not found
    return ''
346197
def is_valid_ip_pattern(ip):
    """"""
    ip = ip.replace('*', '1')
    try:
        socket.inet_aton(ip)
        return True
    except socket.error:
        # Not a valid IPv4 address pattern
        return False
741241
def ip_monitor(self, query, days_back=0, page=1, **kwargs):
        """"""
        return self._results('ip-monitor', '/v1/ip-monitor', query=query, days_back=days_back, page=page,
                            items_path=('alerts', ), **kwargs)
934281
def vt_ip_check(ip, vt_api):
    """"""
    if not is_IPv4Address(ip):
        return None

    url = 'https://www.virustotal.com/vtapi/v2/ip-address/report'
    parameters = {'ip': ip, 'apikey': vt_api}
    response = requests.get(url, params=parameters)
    try:
        return response.json()
    except ValueError:
        return None
987126
def _get_ip(self, interface):
        
        if interface in ni.interfaces():
            addresses = ni.ifaddresses(interface)
            if ni.AF_INET in addresses:
                return addresses[ni.AF_INET][0]["addr"]
        return ""
1021903
def check_internal_ip(request):
    
    remote_addr = (request.META["HTTP_X_FORWARDED_FOR"] if "HTTP_X_FORWARDED_FOR" in request.META else request.META.get("REMOTE_ADDR", ""))
    return remote_addr in settings.INTERNAL_IPS
446770
def scan_ipaddr(ipaddr, apikey):
    
    logger.info('Query VirusTotal API for Public IP Found: %s', ipaddr)
    v_api = virus_total.VirusTotal()
    scan_ip = v_api.send_ip(ipaddr, apikey)
    response_code = scan_ip['response_code']
    verbose_msg = scan_ip['verbose_msg']
    urls = scan_ip['detected_urls']

    if urls:
        failure = True
        logger.error('%s has been known to resolve to malicious urls', ipaddr)
        for url in urls:
            logger.error('%s on date: %s', url['url'], url['scan_date'])
    else:
        logger.info('%s has no record of resolving to malicious urls', ipaddr)
771699
def ip_in_subnet(ip, subnet):
    """"""
    ipaddr = int(''.join(['%02x' % int(x) for x in ip.split('.')]), 16)
    netstr, bits = subnet.split('/')
    netaddr = int(''.join(['%02x' % int(x) for x in netstr.split('.')]), 16)
    mask = (0xffffffff << (32 - int(bits))) & 0xffffffff
    return (ipaddr & mask) == (netaddr & mask)
463940
def getIPaddresses(self):
        """"""
        if not self.ipAddress:
            self.ipAddress = ipAddresses.getAll() # update with IP address
        return self.ipAddress
27302
async def scan_for_units(self, iprange):
        """"""
        units = []
        for ip_address in ipaddress.IPv4Network(iprange):
            sock = socket.socket()
            sock.settimeout(0.02)
            host = str(ip_address)
            try:
                scan_result = sock.connect((host, PORT))
            except socket.error:
                scan_result = 1
            _LOGGER.debug('Checking port connectivity on %s:%s',
                          host, (str(PORT)))
            if scan_result is None:
                ghlocalapi = DeviceInfo(self._loop, self._session, host)
                await ghlocalapi.get_device_info()
                data = ghlocalapi.device_info
                if data is not None:
                    cap = data['device_info']['capabilities']
                    units.append({
                        'host': host,
                        'name': data['name'],
                        'model': data['device_info']['model_name'],
                        'assistant_supported': cap.get('assistant_supported',
                                                       False)
                    })
            sock.close()
        return units
96425
def ip(ip_addr, return_tuple=True):
    
    regex_ip = __re.compile("^((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))$")
    if return_tuple:
        while not regex_ip.match(ip_addr):
            print("Not a good IP.")
            print("Please try again.")
            ip_addr = input("Please enter a IP address in the following format x.x.x.x: ")
        return ip_addr
    elif not return_tuple:
        if not regex_ip.match(ip_addr):
            return False
        else:
            return True
122426
protected function checkIP()
    {
        if (getenv("HTTP_CLIENT_IP"))
            $this->_ip = getenv("HTTP_CLIENT_IP");
        elseif (getenv("HTTP_X_FORWARDED_FOR"))
            $this->_ip = getenv("HTTP_X_FORWARDED_FOR");
        else
            $this->_ip = getenv("REMOTE_ADDR");
    }
1052494
def ip():
    """"""
    ok, err = _hack_ip()
    if not ok:
        click.secho(click.style(err, fg='red'))
        sys.exit(1)
    click.secho(click.style(err, fg='green'))