Fetches country code by IP

    Returns empty string if the request fails in non-200 code.

    Uses the ipdata.co service which has the following rules:

    * Max 1500 requests per day

    See: https://ipdata.co/docs.html#python-library
494092
def fetch_country_by_ip(ip):
    
    iplookup = ipdata.ipdata()
    data = iplookup.lookup(ip)
    if data.get('status') != 200:
        return ''

    return data.get('response', {}).get('country_code', '')
1164296
def download(query, num_results):
	
	# https://stackoverflow.com/questions/11818362/how-to-deal-with-unicode-string-in-url-in-python3
	name = quote(query)

	name  = name.replace(' ','+')
	url = 'http://www.google.com/search?q=' + name
	if num_results != 10:
		url += '&num=' + str(num_results)  # adding this param might hint Google towards a bot
	req = request.Request(url, headers={
		'User-Agent' : choice(user_agents),
		# 'Referer': 'google.com'
	})
	try:
		response = request.urlopen(req)
	except Exception:  # catch connection issues
		# may also catch 503 rate limit exceed
		print('ERROR\n')
		traceback.print_exc()
		return ''
	# response.read is bytes in Py 3
	if isPython2:
		# trick: decode unicode as early as possible
		data = response.read().decode('utf8', errors='ignore')
	else:
		data = str(response.read(), 'utf-8', errors='ignore')
	# print(data)
	return data
1266701
@Nullable
  public static IBANCountryData getCountryData (@Nonnull final String sCountryCode)
  {
    ValueEnforcer.notNull (sCountryCode, "CountryCode");

    return s_aIBANData.get (sCountryCode.toUpperCase (Locale.US));
  }
524702
def urllib_retrieve(url, data=None):
    
    range_limit()
    print "uGET", url
    f = urlopen(url, data)
    html = f.read().decode('utf-8', 'ignore')
    return f.getcode(), html
1049121
private static int parseCountryCode(String countryCode) {

    String normalized = countryCode;
    if (normalized.startsWith(InternationalCallPrefix.PREFIX_PLUS)) {
      normalized = normalized.substring(1);
    } else if (normalized.startsWith(InternationalCallPrefix.PREFIX_00)) {
      normalized = normalized.substring(2);
    } else if (normalized.startsWith(InternationalCallPrefix.PREFIX_011)) {
      normalized = normalized.substring(3);
    }
    if (normalized.startsWith("0")) {
      throw new IllegalArgumentException(countryCode);
    }
    try {
      int cc = Integer.parseInt(normalized);
      return cc;
    } catch (NumberFormatException e) {
      throw new IllegalArgumentException(countryCode, e);
    }
  }
1263172
private static String getIPAddress () {
    String rc;

    try {
      rc = InetAddress.getLocalHost().getHostAddress();
    } catch (Exception e) {
      // No FFDC code needed
      rc = Long.valueOf(new Random().nextLong()).toString();
    }

    return rc;
  }
489431
def get_ip(data):
    '''
    
    '''
    try:
        ip = data.public_ips[0]
    except Exception:
        ip = data.private_ips[0]
    return ip
490729
def get_ip(self):
        
        json_scheme = self.gen_def_json_scheme('GetPurchasedIpAddresses')
        json_obj = self.call_method_post(method='GetPurchasedIpAddresses ', json_scheme=json_scheme)
        self.iplist = IpList()
        for ip in json_obj['Value']:
            r = Ip()
            r.ip_addr = ip['Value']
            r.resid = ip['ResourceId']
            r.serverid = ip['ServerId'] if 'None' not in str(ip['ServerId']) else None
            self.iplist.append(r)
165309
def get_ip(request, real_ip_only=False, right_most_proxy=False):
    
    best_matched_ip = None
    warnings.warn('get_ip is deprecated and will be removed in 3.0.', DeprecationWarning)
    for key in defs.IPWARE_META_PRECEDENCE_ORDER:
        value = request.META.get(key, request.META.get(key.replace('_', '-'), '')).strip()
        if value is not None and value != '':
            ips = [ip.strip().lower() for ip in value.split(',')]
            if right_most_proxy and len(ips) > 1:
                ips = reversed(ips)
            for ip_str in ips:
                if ip_str and is_valid_ip(ip_str):
                    if not ip_str.startswith(NON_PUBLIC_IP_PREFIX):
                        return ip_str
                    if not real_ip_only:
                        loopback = defs.IPWARE_LOOPBACK_PREFIX
                        if best_matched_ip is None:
                            best_matched_ip = ip_str
                        elif best_matched_ip.startswith(loopback) and not ip_str.startswith(loopback):
                            best_matched_ip = ip_str
    return best_matched_ip
322676
def get_ip_address_from_request(request):
    
    remote_addr = request.META.get('REMOTE_ADDR', '')
    if remote_addr and is_valid_ip(remote_addr):
        return remote_addr.strip()
    return '127.0.0.1'
868413
def get_server_by_ip(self, ip_address):
        
        data = self.get_request('/ip_address/{0}'.format(ip_address))
        UUID = data['ip_address']['server']
        return self.get_server(UUID)
518267
public function getHttpCode()
    {
        $code= 200;
        if ($this->errors) {
            /**
             * @var \FreeFW\JsonApi\V1\Model\ErrorObject $oneError
             */
            foreach ($this->errors as $idx => $oneError) {
                if ($oneError->getStatus() > $code) {
                    $code = $oneError->getStatus();
                }
            }
        }
        return $code;
    }
418281
def get(url)

      data = nil
      resp = HTTParty.get(url)

      if resp.code == 200
        return resp.body
      end
    end
320707
def get_country_by_id(self, country_id: int) -> typing.Optional['Country']:
        
        VALID_POSITIVE_INT.validate(country_id, 'get_country_by_id')
        if country_id not in self._countries_by_id.keys():
            for country in self.countries:

                if country.country_id == country_id:
                    self._countries_by_id[country_id] = country
                    return country
            raise ValueError(country_id)
        else:
            return self._countries_by_id[country_id]
1346657
def fetch(self):
        
        LOGGER.debug('Fetching %s, %s', self._path, self._search_values)
        response = self._session.get(self._path, self._search_values,
                                     {'_return_fields': self._return_fields})
        if response.status_code == 200:
            values = response.json()
            self._assign(values)
            return bool(values)
        elif response.status_code >= 400:
            try:
                error = response.json()
                raise exceptions.ProtocolError(error['text'])
            except ValueError:
                raise exceptions.ProtocolError(response.content)
        return False
152871
def describe_ip(ip_address, source='whatismyip'):

    '''  '''
    
# determine url
    if source == 'nekudo':
        source_url = 'https://geoip.nekudo.com/api/%s' % ip_address
    elif source == 'geoip':
        source_url = 'https://freegeoip.net/json/%s' % ip_address
    elif source == 'whatismyip':
        # http://whatismyipaddress.com/ip-lookup
        source_url = 'https://whatismyipaddress.com/ip/%s' % ip_address
    else:
        raise Exception('describe_ip currently only supports queries to nekudo')

    # TODO incorporate geoip module and c dependencies with local database
    # http://tech.marksblogg.com/ip-address-lookups-in-python.html

# send request
    ip_details = {
        'accuracy_radius': 0,
        'asn': '',
        'assignment': '',
        'city': '',
        'continent': '',
        'country': '',
        'hostname': '',
        'ip': '',
        'isp': '',
        'latitude': 0.0,
        'longitude': 0.0,
        'organization': '',
        'postal_code': '',
        'region': '',
        'timezone': '',
        'type': ''
    }
    import requests
    try:
        response = requests.get(url=source_url)
    except Exception as err:
        from labpack.handlers.requests import handle_requests
        from requests import Request
        request_object = Request(method='GET', url=source_url)
        request_details = handle_requests(request_object)
        raise Exception(request_details['error'])

# extract response
    if source == 'whatismyip':
        import re
        response_text = response.content.decode()
        table_regex = re.compile('<table>\n<tr><th>IP.*?</table>\n<span\sstyle', re.S)
        table_search = table_regex.findall(response_text)
        if table_search:
            table_text = table_search[0]
            field_list = [ 'IP', 'Hostname', 'ISP', 'Organization', 'Type', 'ASN', 'Assignment', 'Continent', 'Country', 'State/Region', 'City', 'Latitude', 'Longitude', 'Postal Code']
            for field in field_list:
                field_regex = re.compile('<tr><th>%s:</th><td>(.*?)</td>' % field, re.S)
                field_search = field_regex.findall(table_text)
                if field_search:
                    ip_details[field.lower().replace(' ','_')] = field_search[0]
        for field in ('longitude', 'latitude'):
            if field in ip_details.keys():
                coord_regex = re.compile('\-?\d+\.\d+')
                coord_search = coord_regex.findall(ip_details[field])
                if coord_search:
                    ip_details[field] = float(coord_search[0])
        if 'country' in ip_details.keys():
            country_regex = re.compile('([\w\s]+?)($|\s<img)')
            country_search = country_regex.findall(ip_details['country'])
            if country_search:
                ip_details['country'] = country_search[0][0]
        for field in ('type', 'assignment'):
            if field in ip_details.keys():
                link_regex = re.compile('>(.*?)<')
                link_search = link_regex.findall(ip_details[field])
                if link_search:
                    ip_details[field] = link_search[0]
        if 'state/region' in ip_details.keys():
            ip_details['region'] = ip_details['state/region']
            del ip_details['state/region']
    elif source == 'nekudo':
        response_details = response.json()
        ip_details['country'] = response_details['country']['name']
        ip_details['latitude'] = response_details['location']['latitude']
        ip_details['longitude'] = response_details['location']['longitude']
        ip_details['accuracy_radius'] = response_details['location']['accuracy_radius']
        if response_details['city']:
            ip_details['city'] = response_details['city']
        ip_details['ip'] = response_details['ip']
        for key in response_details.keys():
            if key not in ip_details.keys() and key != 'location':
                ip_details[key] = response_details[key]
    else:
        response_details = response.json()
        for field in ('city', 'ip', 'latitude', 'longitude'):
            ip_details[field] = response_details[field]
        ip_details['country'] = response_details['country_name']
        ip_details['region'] = response_details['region_name']
        ip_details['postal_code'] = response_details['zip_code']
        ip_details['timezone'] = response_details['time_zone']
    
    return ip_details
670628
def _fetch(self, searchtype, fields, **kwargs):
        ''''''
        fields['vintage'] = self.vintage
        fields['benchmark'] = self.benchmark
        fields['format'] = 'json'

        if 'layers' in kwargs:
            fields['layers'] = kwargs['layers']

        returntype = kwargs.get('returntype', 'geographies')
        url = self._geturl(searchtype, returntype)

        try:
            with requests.get(url, params=fields, timeout=kwargs.get('timeout')) as r:
                content = r.json()
                if "addressMatches" in content.get('result', {}):
                    return AddressResult(content)

                if "geographies" in content.get('result', {}):
                    return GeographyResult(content)

                raise ValueError()

        except (ValueError, KeyError):
            raise ValueError("Unable to parse response from Census")

        except RequestException as e:
            raise e