### Run Tests Source: https://github.com/meeb/whoisit/blob/main/README.md Execute the test suite by cloning the repository, installing dependencies, and running the 'make test' command. ```bash $ make test ``` -------------------------------- ### Install whoisit Package Source: https://github.com/meeb/whoisit/blob/main/README.md Install the whoisit library using pip. It has dependencies on 'requests' and 'dateutil'. ```bash pip install whoisit ``` -------------------------------- ### Main Usage Example Source: https://context7.com/meeb/whoisit/llms.txt Demonstrates the main usage patterns: initializing with caching, performing a single IP lookup, looking up domain information, querying ASN details, and running asynchronous batch lookups. ```python if __name__ == '__main__': # Initialize with caching initialize_whoisit() # Single IP lookup info = lookup_ip_info('8.8.8.8') print(f"Google DNS: {info}") # Domain lookup domain_info = whoisit.domain('google.com') print(f"Domain: {domain_info['name']}") print(f"Nameservers: {domain_info['nameservers']}") print(f"Expires: {domain_info['expiration_date']}") # ASN lookup asn_info = whoisit.asn(15169) # Google print(f"ASN: {asn_info['name']}") # Batch async lookups ips = ['1.1.1.1', '8.8.8.8', '208.67.222.222'] results = asyncio.run(batch_lookup_async(ips, 'ip')) for r in results: if 'error' not in r: print(f"{r.get('handle')}: {r.get('name')} ({r.get('country')})") ``` -------------------------------- ### Domain Lookup with Fallback Source: https://github.com/meeb/whoisit/blob/main/README.md This example demonstrates a try-except block to handle potential errors during a domain lookup, falling back to a query with `follow_related=False` if the initial lookup fails, likely due to issues with related RDAP data. ```python try: results = whoisit.domain('example.com') # Assume an error parsing the related RDAP data occurs here except Exception as e: print(f'Failed to look up domain, trying fallback: {e}') results = whoisit.domain('example.com', follow_related=False) # Likely to succeed if the related RDAP data was the issue ``` -------------------------------- ### Get Current Proxy Configuration Source: https://context7.com/meeb/whoisit/llms.txt Retrieves the currently configured HTTP proxy URL. Returns `None` if no proxy is set. ```python import whoisit print(whoisit.get_proxy()) # None whoisit.set_proxy('http://127.0.0.1:8080') print(whoisit.get_proxy()) # 'http://127.0.0.1:8080' ``` -------------------------------- ### Query Entity with Specific RIR Source: https://github.com/meeb/whoisit/blob/main/README.md Use this when an entity might be registered with multiple RIRs or to ensure a specific RIR is queried. The first example shows an unsupported error due to missing RIR information, while the second demonstrates a successful query by specifying the RIR. ```python results = whoisit.entity('AS5089-MNT') # This will work OK because the entity is registered at RIPE results = whoisit.entity('AS5089-MNT', rir='ripe') ``` -------------------------------- ### ASN Query Response Structure Source: https://context7.com/meeb/whoisit/llms.txt Shows the ASN-specific fields, primarily 'asn_range', which is a list containing the start and end of the Autonomous System Number range, alongside common response fields. ```python import whoisit whoisit.bootstrap() # Example IP query showing common response structure result = whoisit.ip('1.1.1.1') # Common fields in all responses common_fields = { 'handle': str, 'parent_handle': str, 'name': str, 'whois_server': str, 'type': str, 'terms_of_service_url': str, 'copyright_notice': str, 'description': list, 'last_changed_date': 'datetime or None', 'registration_date': 'datetime or None', 'expiration_date': 'datetime or None', 'rir': str, 'url': str, 'entities': dict, } # Entities structure - contacts organized by role print(result['entities']) # { # 'abuse': [{'handle': '...', 'name': '...', 'email': '...', 'rir': '...'}], # 'administrative': [...], # 'technical': [...], # 'registrant': [...], # } # IP-specific fields ip_fields = { 'country': str, 'ip_version': int, 'assignment_type': str, 'network': 'IPv4Network or IPv6Network', } # Domain-specific fields domain_result = whoisit.domain('example.com') domain_fields = { 'unicode_name': str, 'nameservers': list, 'status': list, 'dnssec': bool, } # ASN-specific fields asn_result = whoisit.asn(13335) asn_fields = { 'asn_range': list, } ``` -------------------------------- ### Basic Asynchronous RDAP Lookups Source: https://github.com/meeb/whoisit/blob/main/README.md Perform asynchronous lookups for ASNs, domains, IP addresses, and entities using async/await syntax. Requires asynchronous bootstrapping. ```python import whoisit import asyncio async def whoisit_lookups(): results = await whoisit.asn_async(1234) print(results['name']) results = await whoisit.domain_async('example.com') print(results['nameservers']) results = await whoisit.ip_async('1.2.3.4') print(results['name']) results = await whoisit.ip_async('1.2.3.0/24') print(results['name']) results = await whoisit.ip_async('2404:1234:1234:1234:1234:1234:1234:1234') print(results['name']) results = await whoisit.ip_async('2404:1234::/32') print(results['name']) results = await whoisit.entity_async('ARIN') print(results['last_changed_date']) loop = asyncio.get_event_loop() loop.run_until_complete(whoisit.bootstrap_async()) loop.run_until_complete(whoisit_lookups()) loop.close() ``` -------------------------------- ### Including Parsed and Raw RDAP Response Data Source: https://github.com/meeb/whoisit/blob/main/README.md Get both the parsed dictionary and the raw JSON response by using `include_raw=True`. The raw data is accessible via a 'raw' key in the results. ```python results = whoisit.domain('example.com', include_raw=True) # 'results' is the parsed response from whoisit # the raw response can now be accessed as 'results["raw"]' ``` -------------------------------- ### Cache Bootstrap Data with Redis Source: https://github.com/meeb/whoisit/blob/main/README.md Demonstrates caching RDAP bootstrapping data using Redis for persistence and faster retrieval. It checks Redis first, loads if available, otherwise bootstraps and stores in Redis with an expiration. ```python import whoisit import redis r = redis.Redis(host='localhost', port=6379, db=0) bootstrap_info = r.get('whoisit_bootstrap_info') if bootstrap_info: whoisit.load_bootstrap_data(bootstrap_info) else: whoisit.bootstrap() bootstrap_info = whoisit.save_bootstrap_data() expire_in_3_days = 60 * 60 * 24 *3 r.set('whoisit_bootstrap_info', bootstrap_info, ex=expire_in_3_days) ``` -------------------------------- ### Initialize RDAP Bootstrap Data Source: https://context7.com/meeb/whoisit/llms.txt Initializes the whoisit instance by downloading RDAP service discovery information from IANA. This must be called before making any queries. Supports optional overrides for TLDs and allows insecure endpoints. ```python import whoisit # Basic bootstrap - downloads data from IANA whoisit.bootstrap() ``` ```python # Bootstrap with TLD overrides for better domain coverage whoisit.bootstrap(overrides=True) ``` ```python # Allow insecure HTTP endpoints (not recommended) whoisit.bootstrap(allow_insecure=True) ``` ```python # Async bootstrap import asyncio asyncio.run(whoisit.bootstrap_async()) ``` -------------------------------- ### Send normal queries Source: https://github.com/meeb/whoisit/blob/main/README.md After bootstrapping, you can send normal queries using the ASN lookup function. ```python whoisit.asn(12345) ``` -------------------------------- ### Bootstrap with overrides Source: https://github.com/meeb/whoisit/blob/main/README.md Enable overrides to query TLDs with potentially misconfigured RDAP servers in IANA bootstrap data. This allows querying more TLDs by patching IANA data. ```python whoisit.bootstrap(overrides=True) ``` -------------------------------- ### Basic Synchronous RDAP Lookups Source: https://github.com/meeb/whoisit/blob/main/README.md Perform synchronous lookups for ASNs, domains, IP addresses (IPv4/IPv6, CIDR), and entities. Requires bootstrapping the service first. ```python import whoisit whoisit.bootstrap() results = whoisit.asn(1234) print(results['name']) results = whoisit.domain('example.com') print(results['nameservers']) results = whoisit.ip('1.2.3.4') print(results['name']) results = whoisit.ip('1.2.3.0/24') print(results['name']) results = whoisit.ip('2404:1234:1234:1234:1234:1234:1234:1234') print(results['name']) results = whoisit.ip('2404:1234::/32') print(results['name']) results = whoisit.entity('ARIN') print(results['last_changed_date']) ``` -------------------------------- ### Handle WhoisIt Exceptions Source: https://context7.com/meeb/whoisit/llms.txt Demonstrates how to catch specific WhoisIt exceptions for detailed error handling, including QueryError, UnsupportedError, and ResourceDoesNotExist. Also shows how to catch the base WhoisItError. ```python import whoisit from whoisit.errors import ( WhoisItError, BootstrapError, QueryError, UnsupportedError, ParseError, ResourceDoesNotExist, ResourceAccessDeniedError, RateLimitedError, RemoteServerError, ArgumentError, ) whoisit.bootstrap() # Handle specific errors try: result = whoisit.domain('nonexistent.invalidtld') except UnsupportedError as e: print(f"TLD not supported: {e}") except ResourceDoesNotExist as e: print(f"Domain not found: {e}") print(f"Status code: {e.status_code}") # 404 print(f"Response: {e.response}") except RateLimitedError as e: print(f"Rate limited, slow down: {e}") print(f"Status code: {e.status_code}") # 429 except QueryError as e: print(f"Query failed: {e}") print(f"Status code: {e.status_code}") print(f"Response body: {e.response}") except BootstrapError as e: print(f"Bootstrap issue: {e}") # Catch all whoisit exceptions try: result = whoisit.ip('192.168.1.1') # Private IP except WhoisItError as e: print(f"whoisit error: {e}") ``` -------------------------------- ### Initialize whoisit with Bootstrap Caching Source: https://context7.com/meeb/whoisit/llms.txt Initializes the whoisit library, loading bootstrap data from a cache file. It refreshes the cache if it's older than 3 days, otherwise it loads from the file. Handles FileNotFoundError and BootstrapError by bootstrapping and saving. ```python import whoisit from whoisit.errors import ( BootstrapError, QueryError, UnsupportedError, RateLimitedError, ResourceDoesNotExist ) import asyncio import json import time # --- Bootstrap Management --- def initialize_whoisit(cache_file='bootstrap_cache.json'): """Initialize whoisit with cached bootstrap data.""" try: with open(cache_file, 'r') as f: bootstrap_data = f.read() whoisit.load_bootstrap_data(bootstrap_data, overrides=True) # Refresh if older than 3 days if whoisit.bootstrap_is_older_than(days=3): whoisit.clear_bootstrapping() whoisit.bootstrap(overrides=True) with open(cache_file, 'w') as f: f.write(whoisit.save_bootstrap_data()) except (FileNotFoundError, BootstrapError): whoisit.bootstrap(overrides=True) with open(cache_file, 'w') as f: f.write(whoisit.save_bootstrap_data()) ``` -------------------------------- ### Bootstrap with insecure endpoint logging Source: https://github.com/meeb/whoisit/blob/main/README.md Enable debug logging to identify and log insecure RDAP endpoints that are skipped during bootstrapping. This helps in diagnosing connectivity issues. ```python import os os.environ['DEBUG'] = 'true' import whoisit whoisit.bootstrap() ``` -------------------------------- ### Bootstrap WhoisIt Instance Source: https://github.com/meeb/whoisit/blob/main/README.md Initializes the whoisit instance with remote IANA bootstrap data. This method makes HTTP requests and may raise a BootstrapError on failure. ```python whoisit.bootstrap(overrides=bool, allow_insecure=bool) ``` -------------------------------- ### Error Handling for Raw and Include Raw Arguments Source: https://github.com/meeb/whoisit/blob/main/README.md Demonstrates that `raw=True` and `include_raw=True` cannot be used simultaneously, resulting in an `ArgumentError`. ```python results = whoisit.domain('example.com', raw=True, include_raw=True) # This raises a whoisit.errors.ArgumentError ``` -------------------------------- ### Configure HTTP Proxy Source: https://context7.com/meeb/whoisit/llms.txt Configures an HTTP proxy for all subsequent WhoisIt requests. Setting a proxy clears the current session. This should be done before bootstrapping. ```python import whoisit # Set proxy before bootstrapping whoisit.set_proxy('http://127.0.0.1:8080') # All requests now use the proxy whoisit.bootstrap() result = whoisit.ip('1.1.1.1') ``` ```python # Authenticated proxy whoisit.set_proxy('http://user:password@proxy.example.com:3128') ``` -------------------------------- ### Asynchronous Batch Lookups for IP, Domain, or ASN Source: https://context7.com/meeb/whoisit/llms.txt Performs batch lookups asynchronously for IP addresses, domain names, or ASNs. It bootstraps asynchronously and then uses asyncio.gather to run multiple lookups concurrently, returning results or errors. ```python async def batch_lookup_async(items, lookup_type='ip'): """Perform batch lookups asynchronously.""" await whoisit.bootstrap_async(overrides=True) async def lookup_one(item): try: if lookup_type == 'ip': return await whoisit.ip_async(item) elif lookup_type == 'domain': return await whoisit.domain_async(item) elif lookup_type == 'asn': return await whoisit.asn_async(item) except QueryError as e: return {'error': str(e), 'item': item} tasks = [lookup_one(item) for item in items] return await asyncio.gather(*tasks) ``` -------------------------------- ### Bootstrapping Functions Source: https://context7.com/meeb/whoisit/llms.txt Functions for initializing and managing the RDAP service discovery data. This data maps resources to their respective RDAP endpoints and must be loaded before making queries. ```APIDOC ## whoisit.bootstrap() ### Description Initializes the whoisit instance by downloading RDAP service discovery information from IANA. This data maps resources (IP ranges, ASN ranges, TLDs) to their respective RDAP endpoints. Must be called before making any queries. Supports optional overrides for TLDs not properly listed in IANA data and allows insecure (HTTP) endpoints. ### Method `whoisit.bootstrap()` ### Parameters #### Query Parameters - **overrides** (boolean) - Optional - Enable TLD overrides for better domain coverage. - **allow_insecure** (boolean) - Optional - Allow insecure HTTP endpoints (not recommended). ### Request Example ```python import whoisit # Basic bootstrap whoisit.bootstrap() # Bootstrap with TLD overrides whoisit.bootstrap(overrides=True) # Allow insecure HTTP endpoints whoisit.bootstrap(allow_insecure=True) ``` ### Async Bootstrap ```python import asyncio import whoisit asyncio.run(whoisit.bootstrap_async()) ``` ``` ```APIDOC ## whoisit.is_bootstrapped() ### Description Returns a boolean indicating whether bootstrap data has been loaded. Useful for checking state before making queries. ### Method `whoisit.is_bootstrapped()` ### Request Example ```python import whoisit print(whoisit.is_bootstrapped()) # False whoisit.bootstrap() print(whoisit.is_bootstrapped()) # True ``` ``` ```APIDOC ## whoisit.save_bootstrap_data() ### Description Serializes current bootstrap data to a JSON string or Python dictionary for caching. Caching bootstrap data avoids repeated IANA requests and significantly speeds up initialization. ### Method `whoisit.save_bootstrap_data(as_json=True)` ### Parameters #### Query Parameters - **as_json** (boolean) - Optional - If True (default), returns data as a JSON string. If False, returns as a Python dictionary. ### Request Example ```python import whoisit import redis whoisit.bootstrap() # Save bootstrap data as JSON string bootstrap_json = whoisit.save_bootstrap_data() # Store in Redis with 3-day expiration r = redis.Redis(host='localhost', port=6379, db=0) r.set('whoisit_bootstrap', bootstrap_json, ex=60*60*24*3) # Save as Python dict instead of JSON bootstrap_dict = whoisit.save_bootstrap_data(as_json=False) ``` ``` ```APIDOC ## whoisit.load_bootstrap_data() ### Description Loads previously saved bootstrap data from a JSON string or dictionary. Enables fast initialization without HTTP requests to IANA. ### Method `whoisit.load_bootstrap_data(data, from_json=True, overrides=False)` ### Parameters #### Path Parameters - **data** (string or dict) - Required - The bootstrap data to load, either as a JSON string or a Python dictionary. #### Query Parameters - **from_json** (boolean) - Optional - If True (default), assumes `data` is a JSON string. If False, assumes `data` is a Python dictionary. - **overrides** (boolean) - Optional - Enable TLD overrides for better domain coverage. ### Request Example ```python import whoisit import redis r = redis.Redis(host='localhost', port=6379, db=0) bootstrap_json = r.get('whoisit_bootstrap') if bootstrap_json: # Load from cached JSON whoisit.load_bootstrap_data(bootstrap_json) else: # No cache, bootstrap from IANA whoisit.bootstrap() r.set('whoisit_bootstrap', whoisit.save_bootstrap_data(), ex=60*60*24*3) # Load with overrides enabled whoisit.load_bootstrap_data(bootstrap_json, overrides=True) # Load from dict instead of JSON whoisit.load_bootstrap_data(bootstrap_dict, from_json=False) ``` ``` ```APIDOC ## whoisit.bootstrap_is_older_than() ### Description Checks if loaded bootstrap data is older than a specified number of days. Useful for implementing cache refresh logic. ### Method `whoisit.bootstrap_is_older_than(days)` ### Parameters #### Path Parameters - **days** (integer) - Required - The number of days to check against. ### Request Example ```python import whoisit whoisit.bootstrap() # Check if data is older than 3 days if whoisit.bootstrap_is_older_than(days=3): whoisit.clear_bootstrapping() whoisit.bootstrap() # Update your cache with new data new_data = whoisit.save_bootstrap_data() ``` ``` ```APIDOC ## whoisit.clear_bootstrapping() ### Description Clears all stored bootstrap information. Required before loading new bootstrap data. ### Method `whoisit.clear_bootstrapping()` ### Request Example ```python import whoisit whoisit.bootstrap() print(whoisit.is_bootstrapped()) # True whoisit.clear_bootstrapping() print(whoisit.is_bootstrapped()) # False ``` ``` -------------------------------- ### Bootstrap Management Source: https://github.com/meeb/whoisit/blob/main/README.md Functions for managing the bootstrapping process of the WhoisIt library, which is necessary for making remote queries. ```APIDOC ## is_bootstrapped() ### Description Returns boolean True or False if your `whoisit` instance is bootstrapped or not. ### Method GET ### Endpoint `/whoisit/is_bootstrapped` ### Parameters None ### Response #### Success Response (200) - **bootstrapped** (bool) - True if bootstrapped, False otherwise. ### Response Example ```json { "bootstrapped": true } ``` ``` ```APIDOC ## bootstrap(overrides: bool, allow_insecure: bool) ### Description Bootstraps your `whoisit` instance with remote IANA bootstrap information. Returns True or raises a `whoisit.errors.BootstrapError` exception if it fails. This method makes HTTP requests to the IANA. ### Method POST ### Endpoint `/whoisit/bootstrap` ### Parameters #### Query Parameters - **overrides** (bool) - Optional - If True, overrides existing bootstrap data. - **allow_insecure** (bool) - Optional - If True, allows insecure SSL connections. ### Response #### Success Response (200) - **status** (bool) - True if bootstrapping was successful. ### Response Example ```json { "status": true } ``` ``` ```APIDOC ## clear_bootstrapping() ### Description Clears any stored bootstrap information. Always returns boolean True. ### Method DELETE ### Endpoint `/whoisit/clear_bootstrapping` ### Parameters None ### Response #### Success Response (200) - **status** (bool) - Always returns True. ### Response Example ```json { "status": true } ``` ``` ```APIDOC ## save_bootstrap_data() ### Description Returns a string of JSON serialised bootstrap information if any is loaded. If no bootstrap information loaded a `whoisit.errors.BootstrapError` will be raised. ### Method GET ### Endpoint `/whoisit/save_bootstrap_data` ### Parameters None ### Response #### Success Response (200) - **bootstrap_data** (str) - JSON string of bootstrap information. ### Response Example ```json { "bootstrap_data": "{\"iana_servers\": [...], \"iana_last_updated\": ...}" } ``` ``` ```APIDOC ## load_bootstrap_data(data: str, overrides: bool, allow_insecure: bool) ### Description Loads a string of JSON serialised bootstrap data as returned by `save_bootstrap_data()`. Returns True if the data is loaded or raises a `whoisit.errors.BootstrapError` if loading fails. ### Method POST ### Endpoint `/whoisit/load_bootstrap_data` ### Parameters #### Request Body - **data** (str) - Required - JSON string of bootstrap data. #### Query Parameters - **overrides** (bool) - Optional - If True, overrides existing bootstrap data. - **allow_insecure** (bool) - Optional - If True, allows insecure SSL connections. ### Response #### Success Response (200) - **status** (bool) - True if data was loaded successfully. ### Response Example ```json { "status": true } ``` ``` ```APIDOC ## bootstrap_is_older_than(days: int) ### Description Tests if the loaded bootstrap data is older than the specified number of days as an integer. Returns True or False. If no bootstrap information is loaded a `whoisit.errors.BootstrapError` exception will be raised. ### Method GET ### Endpoint `/whoisit/bootstrap_is_older_than` ### Parameters #### Query Parameters - **days** (int) - Required - The number of days to check against. ### Response #### Success Response (200) - **is_older** (bool) - True if bootstrap data is older than the specified days, False otherwise. ### Response Example ```json { "is_older": true } ``` ``` -------------------------------- ### Bootstrap allowing insecure endpoints Source: https://github.com/meeb/whoisit/blob/main/README.md Opt-in to allow insecure (HTTP) RDAP endpoints by setting `allow_insecure=True` during bootstrapping. This expands the range of queryable TLDs. ```python whoisit.bootstrap(allow_insecure=True) ``` -------------------------------- ### Load bootstrap data with overrides Source: https://github.com/meeb/whoisit/blob/main/README.md Load bootstrap data with overrides enabled to patch IANA data for TLDs with misconfigured RDAP servers. This allows querying a wider range of TLDs. ```python whoisit.load_bootstrap_data(bootstrap_info, overrides=True) ``` -------------------------------- ### Async Bootstrap RDAP Data Source: https://github.com/meeb/whoisit/blob/main/README.md Provides an asynchronous interface for bootstrapping RDAP data, suitable for non-blocking applications. ```python await whoisit.bootstrap_async() ``` -------------------------------- ### Query Domain Information Asynchronously Source: https://github.com/meeb/whoisit/blob/main/README.md Asynchronous interface for querying RDAP servers for domain information. Ensure your environment supports async/await. ```python response = await whoisit.domain_async('example.com') ``` -------------------------------- ### Query IP Address Information Asynchronously Source: https://github.com/meeb/whoisit/blob/main/README.md Asynchronous interface for querying RDAP servers for IP address or CIDR information. Ensure your environment supports async/await. ```python response = await whoisit.ip_async('1.1.1.1') ``` -------------------------------- ### whoisit.ip() - IP Address Lookup Source: https://context7.com/meeb/whoisit/llms.txt Queries RDAP for IP address or CIDR network information. Accepts strings, IPv4Address, IPv4Network, IPv6Address, or IPv6Network objects. Returns network allocation details, country, assignment type, and managing entities. ```APIDOC ## whoisit.ip() ### Description Queries RDAP for IP address or CIDR network information. Accepts strings, IPv4Address, IPv4Network, IPv6Address, or IPv6Network objects. Returns network allocation details, country, assignment type, and managing entities. ### Method GET (Implicit) ### Endpoint Not applicable (function call) ### Parameters #### Path Parameters - **ip_address_or_cidr** (string or ipaddress object) - Required - The IP address or CIDR network to query. #### Query Parameters - **rir** (string) - Optional - The Regional Internet Registry to query (e.g., 'arin', 'ripe'). - **raw** (boolean) - Optional - Defaults to False. Whether to return the raw RDAP response. - **include_raw** (boolean) - Optional - Defaults to False. Whether to include the raw RDAP response in the parsed result. ### Request Example ```python import whoisit from ipaddress import IPv4Address, IPv4Network whoisit.bootstrap() result = whoisit.ip('1.1.1.1') result_cidr = whoisit.ip(IPv4Network('8.8.8.0/24')) ``` ### Response #### Success Response (200) - **name** (string) - The name of the network allocation. - **handle** (string) - The handle of the network allocation. - **country** (string) - The country code of the allocation. - **ip_version** (integer) - The IP version (4 or 6). - **network** (ipaddress object) - The IP network object. - **assignment_type** (string) - The type of IP address assignment. - **rir** (string) - The Regional Internet Registry that manages the allocation. - **description** (list) - A list of descriptions for the network. #### Response Example ```json { "name": "APNIC-LABS", "handle": "1.1.1.0 - 1.1.1.255", "country": "AU", "ip_version": 4, "network": "1.1.1.0/24", "assignment_type": "assigned portable", "rir": "apnic", "description": ["APNIC and Cloudflare DNS Resolver project"] } ``` ### Async Query Example ```python import asyncio import whoisit result = asyncio.run(whoisit.ip_async('1.1.1.1')) ``` ``` -------------------------------- ### Query Entity Information Asynchronously Source: https://github.com/meeb/whoisit/blob/main/README.md Asynchronous interface for querying RDAP servers for entity information. Ensure your environment supports async/await. ```python response = await whoisit.entity_async('ZG39-ARIN') ``` -------------------------------- ### Load bootstrap data allowing insecure endpoints Source: https://github.com/meeb/whoisit/blob/main/README.md Load bootstrap data while allowing insecure (HTTP) endpoints by using the `allow_insecure=True` argument. This is useful when RDAP servers only support HTTP. ```python whoisit.load_bootstrap_data(bootstrap_info, allow_insecure=True) ``` -------------------------------- ### Set HTTP proxy for requests Source: https://github.com/meeb/whoisit/blob/main/README.md Specify an HTTP proxy to be used for all `whoisit` requests, including bootstrapping and IP queries. The proxy is set using the `set_proxy` method. ```python whoisit.set_proxy('http://127.0.0.1:8080') # Both bootstrapping and the IP query for 1.1.1.1 will use the proxy at http://127.0.0.1:8080 whoisit.bootstrap() result = whoisit.ip('1.1.1.1') ``` -------------------------------- ### Query IP Address Information Source: https://github.com/meeb/whoisit/blob/main/README.md Performs an IP query for a given IPv4 address and prints the full response. Requires the whoisit library to be bootstrapped. ```python import whoisit whoisit.bootstrap() response = whoisit.ip('1.1.1.1') print(response) ``` -------------------------------- ### IP Query Response Structure Source: https://context7.com/meeb/whoisit/llms.txt Illustrates the common and IP-specific fields returned by the whoisit.ip() query. Common fields include handle, name, and RIR, while IP-specific fields detail country, IP version, and network assignment. ```python import whoisit whoisit.bootstrap() # Example IP query showing common response structure result = whoisit.ip('1.1.1.1') # Common fields in all responses common_fields = { 'handle': str, 'parent_handle': str, 'name': str, 'whois_server': str, 'type': str, 'terms_of_service_url': str, 'copyright_notice': str, 'description': list, 'last_changed_date': 'datetime or None', 'registration_date': 'datetime or None', 'expiration_date': 'datetime or None', 'rir': str, 'url': str, 'entities': dict, } # Entities structure - contacts organized by role print(result['entities']) # { # 'abuse': [{'handle': '...', 'name': '...', 'email': '...', 'rir': '...'}], # 'administrative': [...], # 'technical': [...], # 'registrant': [...], # } # IP-specific fields ip_fields = { 'country': str, 'ip_version': int, 'assignment_type': str, 'network': 'IPv4Network or IPv6Network', } ``` -------------------------------- ### Synchronous IP Address Lookup with Error Handling Source: https://context7.com/meeb/whoisit/llms.txt Performs a synchronous lookup for IP address information, returning a dictionary with details like name, network, country, and abuse contacts. Includes specific error handling for ResourceDoesNotExist, RateLimitedError (with retry), and general QueryError. ```python def lookup_ip_info(ip_address): """Look up IP information with error handling.""" try: result = whoisit.ip(ip_address) return { 'ip': ip_address, 'name': result.get('name'), 'network': str(result.get('network')), 'country': result.get('country'), 'rir': result.get('rir'), 'abuse_contacts': [ e.get('email') for e in result.get('entities', {}).get('abuse', []) ] } except ResourceDoesNotExist: return {'ip': ip_address, 'error': 'Not found'} except RateLimitedError: time.sleep(60) # Back off on rate limiting return lookup_ip_info(ip_address) # Retry except QueryError as e: return {'ip': ip_address, 'error': str(e)} ``` -------------------------------- ### whoisit.domain() - Domain Lookup Source: https://context7.com/meeb/whoisit/llms.txt Queries RDAP for domain registration information. Returns nameservers, status, DNSSEC info, registrar details, and registration/expiration dates. Automatically follows related RDAP endpoints for more detailed information. ```APIDOC ## whoisit.domain() ### Description Queries RDAP for domain registration information. Returns nameservers, status, DNSSEC info, registrar details, and registration/expiration dates. Automatically follows related RDAP endpoints for more detailed information. ### Method GET (Implicit) ### Endpoint Not applicable (function call) ### Parameters #### Query Parameters - **domain_name** (string) - Required - The domain name to query. - **follow_related** (boolean) - Optional - Defaults to True. Whether to follow related RDAP endpoints. - **raw** (boolean) - Optional - Defaults to False. Whether to return the raw RDAP response. - **include_raw** (boolean) - Optional - Defaults to False. Whether to include the raw RDAP response in the parsed result. - **allow_insecure_ssl** (boolean) - Optional - Defaults to False. Whether to allow insecure SSL connections. ### Request Example ```python import whoisit whoisit.bootstrap() result = whoisit.domain('cloudflare.com') ``` ### Response #### Success Response (200) - **name** (string) - The domain name. - **nameservers** (list) - A list of nameservers for the domain. - **status** (list) - A list of status codes for the domain. - **dnssec** (boolean) - Indicates if DNSSEC is enabled. - **expiration_date** (datetime) - The domain's expiration date. - **registration_date** (datetime) - The domain's registration date. - **entities** (list) - A list of entities associated with the domain (registrar, registrant, etc.). #### Response Example ```json { "name": "cloudflare.com", "nameservers": ["ns1.cloudflare.com", "ns2.cloudflare.com"], "status": ["client transfer prohibited"], "dnssec": true, "expiration_date": "2025-08-08T04:00:00Z", "registration_date": "2009-09-10T17:00:00Z", "entities": [ { "handle": "Z1988-CNIC", "name": "Cloudflare, Inc.", "type": "registrant", "contact": { "name": "Cloudflare, Inc.", "email": "dns-compliance@cloudflare.com" } } ] } ``` ### Async Query Example ```python import asyncio import whoisit result = asyncio.run(whoisit.domain_async('example.com')) ``` ``` -------------------------------- ### Load bootstrap data as Python dictionary Source: https://github.com/meeb/whoisit/blob/main/README.md Load bootstrap data as a Python dictionary by setting `as_json=False`. This enables custom serialization handling within your application. ```python whoisit.load_bootstrap_data(some_data, as_json=False) ``` -------------------------------- ### Load WhoisIt Bootstrap Data Source: https://github.com/meeb/whoisit/blob/main/README.md Loads bootstrap data from a JSON string. Use this to initialize whoisit with previously saved data. Raises BootstrapError on failure. ```python whoisit.load_bootstrap_data(data=str, overrides=bool, allow_insecure=bool) ``` -------------------------------- ### Session and Proxy Management Source: https://context7.com/meeb/whoisit/llms.txt Functions for managing the HTTP proxy used by the WhoisIt library. ```APIDOC ## Session and Proxy Management ### whoisit.set_proxy() #### Description Configures an HTTP proxy for all whoisit requests. Both bootstrapping and query requests will use the specified proxy. Setting a proxy clears the current session. ### Method Not applicable (function call) ### Endpoint Not applicable (function call) ### Parameters #### Path Parameters - **proxy_url** (string) - Required - The URL of the HTTP proxy (e.g., 'http://user:password@proxy.example.com:3128'). ### Request Example ```python import whoisit whoisit.set_proxy('http://127.0.0.1:8080') whoisit.bootstrap() result = whoisit.ip('1.1.1.1') ``` ### whoisit.get_proxy() #### Description Returns the currently configured proxy URL or None if no proxy is set. ### Method Not applicable (function call) ### Endpoint Not applicable (function call) ### Request Example ```python import whoisit print(whoisit.get_proxy()) # None whoisit.set_proxy('http://127.0.0.1:8080') print(whoisit.get_proxy()) # 'http://127.0.0.1:8080' ``` ``` -------------------------------- ### Asynchronous Lookups Source: https://github.com/meeb/whoisit/blob/main/README.md Provides asynchronous versions of the domain, IP, and entity lookup functions for non-blocking operations. ```APIDOC ## Asynchronous API ### Description As of `whoisit` version 3.0.0, asynchronous interfaces are available for domain, IP, and entity lookups. ### Methods - `whoisit.domain_async(domain: str, ...)` - `whoisit.ip_async(ip: str, ...)` - `whoisit.entity_async(entity: str, ...)` ### Request Example ```python response_domain = await whoisit.domain_async('example.com') response_ip = await whoisit.ip_async('1.1.1.1') response_entity = await whoisit.entity_async('ZG39-ARIN') ``` ### Response #### Success Response (200) - **dict** - A dictionary containing information about the queried resource, similar to the synchronous responses. ``` -------------------------------- ### Save bootstrap data as Python dictionary Source: https://github.com/meeb/whoisit/blob/main/README.md Save bootstrap data as a Python dictionary by setting `as_json=False`. This allows custom serialization in your application. ```python whoisit.save_bootstrap_data(as_json=False) ``` -------------------------------- ### Enable Debug Logging in whoisit Source: https://github.com/meeb/whoisit/blob/main/README.md Set the DEBUG environment variable to 'true' (or '1', 'y', etc.) to enable detailed debug logs for bootstrapping, requests, and parsing operations. This is useful for understanding the internal workings of the library. ```bash $ export DEBUG=true $ python3 some-script-that-uses-whoisit.py ``` -------------------------------- ### Bootstrap RDAP Data Management Source: https://github.com/meeb/whoisit/blob/main/README.md Manage RDAP bootstrapping data for efficient querying. This includes checking if bootstrapped, performing the bootstrap, saving/loading data, clearing it, and checking data age for refreshing. ```python import whoisit print(whoisit.is_bootstrapped()) # -> False whoisit.bootstrap() # Slow, makes several HTTP requests to the IANA print(whoisit.is_bootstrapped()) # -> True # bootstrap_info returned here is a string of JSON serialised bootstap information # You can store it in a memory cache or write it to disk for a few days bootstrap_info = whoisit.save_bootstrap_data() # Clear bootstrapping data whoisit.clear_bootstrapping() # Later, you can do print(whoisit.is_bootstrapped()) # -> False if not whoisit.is_bootstrapped(): whoisit.load_bootstrap_data(bootstrap_info) # Fast, no HTTP requests made print(whoisit.is_bootstrapped()) # -> True # For convenience internally whoisit stores a timestamp of when the bootstrap data was # last updated and has a "is older than" helper method if whoisit.bootstrap_is_older_than(days=3): # Bootstrap data was last updated over 3 days ago, refresh it whoisit.clear_bootstrapping() whoisit.bootstrap() bootstrap_info = whoisit.save_bootstrap_data() # and save it to upload your cache ``` -------------------------------- ### Specifying RDAP Service for Entity Lookups Source: https://github.com/meeb/whoisit/blob/main/README.md When an entity handle does not have an obvious RIR prefix/postfix, explicitly specify the RIR using the `rir` argument to avoid `QueryError`. ```python # This will work OK because the entity is prefixed with an obvious RIR name results = whoisit.entity('RIPE-NCC-MNT') # This will cause a QueryError to be raised because ARIN returns a 404 for RIPE-NCC-MNT results = whoisit.entity('RIPE-NCC-MNT', rir='arin') ``` -------------------------------- ### Check if WhoisIt is Bootstrapped Source: https://github.com/meeb/whoisit/blob/main/README.md Returns a boolean indicating whether the whoisit instance has been successfully bootstrapped with remote IANA information. ```python whoisit.is_bootstrapped() ``` -------------------------------- ### Load bootstrap data as JSON Source: https://github.com/meeb/whoisit/blob/main/README.md Load bootstrap data from a JSON encoded string. The default operation loads bootstrap data from a JSON encoded string. ```python whoisit.load_bootstrap_data(some_data, as_json=True) ``` -------------------------------- ### Query Functions Source: https://context7.com/meeb/whoisit/llms.txt Functions for querying RDAP services for various internet resources. These functions require bootstrap data to be loaded first. ```APIDOC ## whoisit.asn() ### Description Queries RDAP for information about an Autonomous System Number (ASN). Returns parsed data including ASN range, name, handle, registration dates, and associated entities with contact information. ### Method `whoisit.asn(asn, rir=None, raw=False, include_raw=False, allow_insecure_ssl=False)` ### Parameters #### Path Parameters - **asn** (integer) - Required - The Autonomous System Number to query. #### Query Parameters - **rir** (string) - Optional - Specify a particular RIR to query (e.g., 'arin', 'ripe'). If not provided, the library will attempt to discover the correct RIR. - **raw** (boolean) - Optional - If True, returns the raw JSON response from the RDAP service without parsing. - **include_raw** (boolean) - Optional - If True, includes the raw RDAP JSON response within the parsed dictionary under the 'raw' key. - **allow_insecure_ssl** (boolean) - Optional - Allows connections to RDAP services with weaker SSL implementations. ### Request Example ```python import whoisit whoisit.bootstrap() # Query by AS number result = whoisit.asn(13335) print(result['name']) # 'CLOUDFLARENET' print(result['handle']) # 'AS13335' print(result['asn_range']) # [13335, 13335] print(result['rir']) # 'arin' print(result['registration_date']) # datetime object print(result['entities']) # Dict of contacts by role # Query with specific RIR override result = whoisit.asn(12345, rir='ripe') # Get raw RDAP JSON response raw_result = whoisit.asn(13335, raw=True) # Get parsed result with raw data included result = whoisit.asn(13335, include_raw=True) print(result['raw']) # Full RDAP response # Handle weaker SSL implementations result = whoisit.asn(12345, allow_insecure_ssl=True) ``` ``` -------------------------------- ### Proxy and Session Management Source: https://context7.com/meeb/whoisit/llms.txt Functions to manage proxy settings and clear session data for network requests. ```APIDOC ## clear_proxy() ### Description Removes proxy configuration. Subsequent requests will be made directly. Also clears the current session. ### Method N/A (Function Call) ### Endpoint N/A ### Request Example ```python import whoisit whoisit.set_proxy('http://127.0.0.1:8080') whoisit.bootstrap() # Clear proxy for direct connections whoisit.clear_proxy() # This request goes direct result = whoisit.domain('example.com') ``` ## clear_session() ### Description Resets HTTP connection pools. Useful when you need to force new connections or after network configuration changes. ### Method N/A (Function Call) ### Endpoint N/A ### Request Example ```python import whoisit whoisit.bootstrap() result = whoisit.ip('1.1.1.1') # Reset all connection pools whoisit.clear_session() # New connections will be established result = whoisit.ip('8.8.8.8') ``` ``` -------------------------------- ### Handle SSL Errors with Insecure SSL Source: https://github.com/meeb/whoisit/blob/main/README.md Use `allow_insecure_ssl=True` when encountering SSL errors like 'DH_KEY_TOO_SMALL' from RDAP servers. This weakens SSL ciphers but still validates the certificate. Only use if direct requests fail due to SSL issues. ```python # This will result in an SSL error results = whoisit.domain('nic.work') # ... SSLError(SSLError(1, '[SSL: DH_KEY_TOO_SMALL] dh key too small (_ssl.c:1129)')) # This will work results = whoisit.domain('nic.work', allow_insecure_ssl=True) ``` -------------------------------- ### Clear Proxy Configuration Source: https://context7.com/meeb/whoisit/llms.txt Removes proxy settings and clears the current session, forcing subsequent requests to be made directly. Ensure bootstrap is called before setting proxies. ```python import whoisit whoisit.set_proxy('http://127.0.0.1:8080') whoisit.bootstrap() # Clear proxy for direct connections whoisit.clear_proxy() # This request goes direct result = whoisit.domain('example.com') ``` -------------------------------- ### Query Entity Information Source: https://github.com/meeb/whoisit/blob/main/README.md Query RDAP servers for entity information using an entity handle. Supports specifying an RIR and retrieving raw data. Raises QueryError, BootstrapError, or UnsupportedError on failure. ```python whoisit.entity('ZG39-ARIN') ``` ```python whoisit.entity('ZG39-ARIN', rir='arin') ``` ```python whoisit.entity('ZG39-ARIN', rir='arin', raw=True) ``` ```python whoisit.entity('ZG39-ARIN', rir='arin', include_raw=True) ``` ```python whoisit.entity('ZG39-ARIN', allow_insecure_ssl=True) ``` -------------------------------- ### Load Cached Bootstrap Data Source: https://context7.com/meeb/whoisit/llms.txt Loads previously saved bootstrap data from a JSON string or dict. Enables fast initialization without HTTP requests to IANA. Supports loading with overrides enabled and from a Python dict. ```python import whoisit import redis r = redis.Redis(host='localhost', port=6379, db=0) bootstrap_json = r.get('whoisit_bootstrap') if bootstrap_json: # Load from cached JSON whoisit.load_bootstrap_data(bootstrap_json) else: # No cache, bootstrap from IANA whoisit.bootstrap() r.set('whoisit_bootstrap', whoisit.save_bootstrap_data(), ex=60*60*24*3) # Load with overrides enabled whoisit.load_bootstrap_data(bootstrap_json, overrides=True) # Load from dict instead of JSON whoisit.load_bootstrap_data(bootstrap_dict, from_json=False) ``` -------------------------------- ### Save bootstrap data as JSON Source: https://github.com/meeb/whoisit/blob/main/README.md Save bootstrap data as a JSON encoded string. The default operation returns bootstrap data as a JSON encoded string. ```python whoisit.save_bootstrap_data(as_json=True) ```