Skip to main content

geolocalizar_ip_metodo1()

Primary IP geolocation method using the ip-api.com service. This method provides comprehensive geolocation data including ISP information and does not require an API key.

Function Signature

def geolocalizar_ip_metodo1(ip_address: str) -> dict | None

Parameters

ip_address
string
required
The IPv4 address to geolocate. Must be a valid IP address format (e.g., “8.8.8.8”). Private IP addresses will return an error from the API.

Return Value

response
dict | None
Returns a dictionary with geolocation data on success, or None if the request fails.

Response Data Structure

query
string
The IP address that was queried
country
string
Full country name (e.g., “United States”)
countryCode
string
Two-letter country code (e.g., “US”)
regionName
string
Region or state name
city
string
City name
zip
string
Postal/ZIP code
lat
float
Latitude coordinate
lon
float
Longitude coordinate
timezone
string
Timezone identifier (e.g., “America/New_York”)
isp
string
Internet Service Provider name
org
string
Organization name
as
string
Autonomous System information

Code Example

from tracker import geolocalizar_ip_metodo1, validar_ip

# Validate and geolocate an IP address
ip = "8.8.8.8"

if validar_ip(ip):
    resultado = geolocalizar_ip_metodo1(ip)
    
    if resultado:
        print(f"País: {resultado['country']}")
        print(f"Ciudad: {resultado['city']}")
        print(f"ISP: {resultado['isp']}")
        print(f"Coordenadas: {resultado['lat']}, {resultado['lon']}")
    else:
        print("Error al obtener información de geolocalización")
else:
    print("Dirección IP inválida")

Side Effects

  • Creates Resultados_Tracker/ directory if it doesn’t exist
  • Saves results to a text file: IP_{ip_address}_{timestamp}.txt
  • Prints formatted output to console with colored text
  • Includes Google Maps URL in output file

Exceptions and Error Handling

requests.exceptions.Timeout
exception
Raised when the API request exceeds 10 seconds. Function catches this and returns None.
requests.exceptions.ConnectionError
exception
Raised when unable to connect to the API server. Function catches this and returns None.
HTTP Status != 200
error
If the API returns a non-200 status code, the function prints an error and returns None.
API status: 'fail'
error
If the API returns status: 'fail' in the response (e.g., for invalid or private IPs), the function prints the error message and returns None.

API Details

  • Endpoint: http://ip-api.com/json/{ip_address}
  • Method: GET
  • Timeout: 10 seconds
  • Rate Limit: Free tier allows 45 requests per minute
  • Authentication: None required

geolocalizar_ip_metodo2()

Alternative IP geolocation method using the ipinfo.io service. Provides similar data with slightly different field names and structure.

Function Signature

def geolocalizar_ip_metodo2(ip_address: str) -> dict | None

Parameters

ip_address
string
required
The IPv4 address to geolocate. Must be a valid IP address format (e.g., “8.8.8.8”).

Return Value

response
dict | None
Returns a dictionary with geolocation data on success, or None if the request fails.

Response Data Structure

ip
string
The IP address that was queried
hostname
string
Hostname associated with the IP address
city
string
City name
region
string
Region or state name
country
string
Two-letter country code (e.g., “US”)
postal
string
Postal/ZIP code
loc
string
Comma-separated latitude and longitude (e.g., “37.751,-97.822”)
org
string
Organization name (typically includes AS number and ISP)
timezone
string
Timezone identifier (e.g., “America/Chicago”)

Code Example

from tracker import geolocalizar_ip_metodo2, validar_ip

# Geolocate using the alternative method
ip = "1.1.1.1"

if validar_ip(ip):
    resultado = geolocalizar_ip_metodo2(ip)
    
    if resultado:
        # Parse coordinates from loc field
        loc = resultado['loc'].split(',')
        lat, lon = loc[0], loc[1]
        
        print(f"IP: {resultado['ip']}")
        print(f"Hostname: {resultado.get('hostname', 'N/A')}")
        print(f"País: {resultado['country']}")
        print(f"Ciudad: {resultado['city']}")
        print(f"Coordenadas: {lat}, {lon}")
        print(f"Organización: {resultado['org']}")
    else:
        print("Error al obtener información")
else:
    print("IP inválida")

Side Effects

  • Creates Resultados_Tracker/ directory if it doesn’t exist
  • Saves results to a text file: IP_{ip_address}_metodo2_{timestamp}.txt
  • Prints formatted output to console with colored text
  • Includes Google Maps URL in output file
  • Parses loc field to separate latitude and longitude

Exceptions and Error Handling

requests.exceptions.Timeout
exception
Raised when the API request exceeds 10 seconds. Function catches this and returns None.
requests.exceptions.ConnectionError
exception
Raised when unable to connect to the API server. Function catches this and returns None.
HTTP Status != 200
error
If the API returns a non-200 status code, the function prints an error and returns None.
'error' in response
error
If the API returns an error object in the response, the function prints the error message and returns None.

API Details

  • Endpoint: https://ipinfo.io/{ip_address}/json
  • Method: GET
  • Timeout: 10 seconds
  • Rate Limit: Free tier allows 50,000 requests per month
  • Authentication: None required (free tier)

Comparison: Method 1 vs Method 2

FeatureMethod 1 (ip-api.com)Method 2 (ipinfo.io)
ISP FieldSeparate isp fieldIncluded in org field
CountryFull name + codeCode only
HostnameNot providedProvided
AS InfoSeparate as fieldIncluded in org field
CoordinatesSeparate lat/lonCombined loc string
Rate Limit45 req/min50k req/month

Best Practices

  1. Always validate the IP address using validar_ip() before calling geolocation methods
  2. Handle None returns - Check if the return value is None before accessing data
  3. Use Method 1 for more detailed ISP information
  4. Use Method 2 for hostname resolution
  5. Implement retry logic for production use cases to handle transient network errors
  6. Check rate limits if making multiple requests

Build docs developers (and LLMs) love