Get geographic coordinates from IP using geoip database
493326
def locate_ip(ip):
    """"""
    ip=map(int,ip.split("."))
    ip = ip[3]+(ip[2]<<8)+(ip[1]<<16)+(ip[0]<<24)

    cloc = country_loc_kdb.get_base()
    db = IP_country_kdb.get_base()

    d=0
    f=len(db)-1
    while (f-d) > 1:
        guess = (d+f)/2
        if ip > db[guess][0]:
            d = guess
        else:
            f = guess
    s,e,c = db[guess]
    if  s <= ip and ip <= e:
        return cloc.get(c,None)
1167100
def get_ip_address_from_request(request):
    
    PRIVATE_IPS_PREFIX = ('10.', '172.', '192.', '127.')
    ip_address = ''
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR', '')
    if x_forwarded_for and ',' not in x_forwarded_for:
        if not x_forwarded_for.startswith(PRIVATE_IPS_PREFIX) and is_valid_ip(x_forwarded_for):
            ip_address = x_forwarded_for.strip()
    else:
        ips = [ip.strip() for ip in x_forwarded_for.split(',')]
        for ip in ips:
            if ip.startswith(PRIVATE_IPS_PREFIX):
                continue
            elif not is_valid_ip(ip):
                continue
            else:
                ip_address = ip
                break
    if not ip_address:
        x_real_ip = request.META.get('HTTP_X_REAL_IP', '')
        if x_real_ip:
            if not x_real_ip.startswith(PRIVATE_IPS_PREFIX) and is_valid_ip(x_real_ip):
                ip_address = x_real_ip.strip()
    if not ip_address:
        remote_addr = request.META.get('REMOTE_ADDR', '')
        if remote_addr:
            if not remote_addr.startswith(PRIVATE_IPS_PREFIX) and is_valid_ip(remote_addr):
                ip_address = remote_addr.strip()
            if remote_addr.startswith(PRIVATE_IPS_PREFIX) and is_valid_ip(remote_addr):
                ip_address = remote_addr.strip()
    if not ip_address:
            ip_address = '127.0.0.1'
    return ip_address
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)
1139366
function resolve($ip){
      
      $url = \Config::get('laravel-4-freegeoip::freegeoipURL').$ip;
      
      $ch = curl_init();
      curl_setopt ($ch, CURLOPT_URL, $url);
      curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, \Config::get('laravel-4-freegeoip::timeout'));
      
      $file_contents = curl_exec($ch);    
      curl_close($ch);
      
      $data = json_decode($file_contents);
      
      if($data == NULL)
          throw new \Exception("Problems in retrieving data from http://freegeoip.net");

      return $data;
    }
423360
def _get_local_ip(self):
        """"""
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

            # Use Google Public DNS server to determine own IP
            sock.connect(('8.8.8.8', 80))

            return sock.getsockname()[0]
        except socket.error:
            try:
                return socket.gethostbyname(socket.gethostname())
            except socket.gaierror:
                return '127.0.0.1'
        finally:
            sock.close()
484209
def get_ip():
    
    try:
        r = requests.get(HTTPBIN_URL)
        ip, _ = r.json()['origin'].split(',')
        return ip if r.status_code == 200 else None
    except requests.exceptions.ConnectionError:
        return None
606822
def get_latlon(self, use_cached=True):
        """"""
        device_json = self.get_device_json(use_cached)
        lat = device_json.get("dpMapLat")
        lon = device_json.get("dpMapLong")
        return (float(lat) if lat else None,
                float(lon) if lon else None, )
545526
def __getIP(self, public):
        """"""

        maybeNot = (lambda x: x) if public else (lambda x: not x)
        nets_id = [net.id for net in self.networks if maybeNot(net.isPublic())]
        for s in self.systems:
            i = 0
            while True:
                value = s.getValue("net_interface.%d.connection" % i)
                if not value:
                    break
                if value in nets_id:
                    ip = s.getValue("net_interface.%d.ip" % i)
                    if ip:
                        return ip
                i += 1
        return None
742938
def locate(self):
        
        stored_location = self._get_stored_location()
        if not stored_location:
            ip_range = self._get_ip_range()
            stored_location = self._get_corresponding_location(ip_range)
        return stored_location
599829
def get_geo_region(self, ip):
        
        query_parameters = {}
        if ip is not None:
            query_parameters['ip'] = self._serialize.query('ip', ip, 'str')
        response = self._send(http_method='GET',
                              location_id='35b3ff1d-ab4c-4d1c-98bb-f6ea21d86bd9',
                              version='5.1-preview.1',
                              query_parameters=query_parameters)
        return self._deserialize('GeoRegion', response)
346778
def get_location(address=""):
    
    coordinates = None
    try:
        geolocator = Nominatim()
        location = geolocator.geocode(address)
        coordinates = (location.latitude, location.longitude)
    except Exception as ex:
        logger.error('Fail get location - {}'.format(ex))
    return coordinates
1218881
def get_location (host):
    
    if geoip is None:
        # no geoip available
        return None
    try:
        record = get_geoip_record(host)
    except (geoip_error, socket.error):
        log.debug(LOG_PLUGIN, "Geoip error for %r", host, exception=True)
        # ignore lookup errors
        return None
    value = u""
    if record and record.get("city"):
        value += unicode_safe(record["city"])
    if record and record.get("country_name"):
        if value:
            value += u", "
        value += unicode_safe(record["country_name"])
    return value
1263802
def _build_query(self, ip_address):
        
        return '{}.{}.{}'.format(
            self.key, self._reverse_ip(ip_address), DNSBL_SUFFIX)
1335172
public function getRaw()
    {
        $ip = $this->getIp();
        $this->setIp($ip);

        // check ip in memory
        $data = array_get($this->storeRaw, $ip);

        if (! $data) {
            try {
                $data = $this->getDriver()->getRaw($ip);
            } catch (\Exception $e) {
                throw new GeoIPException('Failed to get raw geoip data', 0, $e);
            }

            // cache ip data in memory
            $this->storeRaw[$ip] = $data;
        }

        return $data;
    }
554958
def _ip2country(ip):
    """"""
    if ip:
        match = geolite2.reader().get(ip)
        return match.get('country', {}).get('iso_code') if match else None
1238357
def get_ip(self, use_cached=True):
        """"""
        device_json = self.get_device_json(use_cached)
        return device_json.get("dpLastKnownIp")
915671
def _get(self, ip):
        
        # Geoloc updated up to once a week:
        # http://ipinfo.io/developers/data#geolocation-data
        retries = 10
        for retry in range(retries):
            try:
                response = requests.get('http://ipinfo.io/%s/json' % ip,
                                        verify=False, timeout=1)  # nosec
                if response.status_code == 429:
                    raise RateExceededError
                return response.json()
            except (requests.ReadTimeout, requests.ConnectTimeout):
                pass
        return {}