Ejemplo n.º 1
0
def get_ipv4_geolocation(remote_addr,
                         ipv4_table=model.MaxmindCityBlock,
                         city_table=model.MaxmindCityLocation):
    """Returns the geolocation data associated with an IPv4 address.

    Args:
        remote_addr: A string describing an IPv4 address.

    Returns:
        A GeoRecord containing the geolocation data if is found in the db,
        otherwise an empty GeoRecord.

    Raises:
        ipaddr.AddressValueError, if 'remote_addr' is not a valid IPv4 address.
    """
    geo_record = GeoRecord()
    ip_num = int(ipaddr.IPv4Address(remote_addr))

    geo_city_block = ipv4_table.gql(
        'WHERE start_ip_num <= :ip_num '
        'ORDER BY start_ip_num DESC',
        ip_num=ip_num).get()
    if geo_city_block is None or geo_city_block.end_ip_num < ip_num:
        logging.error('IP %s not found in the Maxmind database.', str(ip_num))
        return geo_record

    location = city_table.get_by_key_name(geo_city_block.location_id)
    if location is None:
        logging.error(
            'Location %s not found in the Maxmind database.', remote_addr)
        return geo_record

    geo_record.city = location.city
    geo_record.country = location.country
    geo_record.latitude = location.latitude
    geo_record.longitude = location.longitude
    return geo_record
Ejemplo n.º 2
0
def _is_valid_ipv4(ip):
    try:
        ipaddr.IPv4Address(ip)
        return True
    except ipaddr.AddressValueError:
        return False