Library Structure

class ipwhois.ipwhois.IPWhois(address, timeout=5, proxy_opener=None, allow_permutations=True)[source]

The wrapper class for performing whois/RDAP lookups and parsing for IPv4 and IPv6 addresses.

Parameters:
  • address – An IPv4 or IPv6 address as a string, integer, IPv4Address, or IPv6Address.
  • timeout – The default timeout for socket connections in seconds.
  • proxy_opener – The urllib.request.OpenerDirector request for proxy support or None.
  • allow_permutations – allow net.Net() to use additional methods if DNS lookups to Cymru fail.
lookup(*args, **kwargs)[source]

Temporary wrapper for legacy whois lookups (moved to IPWhois.lookup_whois()). This will be removed in a future release (1.0.0).

lookup_rdap(inc_raw=False, retry_count=3, depth=0, excluded_entities=None, bootstrap=False, rate_limit_timeout=120, asn_alts=None, extra_org_map=None, inc_nir=True, nir_field_list=None)[source]

The function for retrieving and parsing whois information for an IP address via HTTP (RDAP).

This is now the recommended method, as RDAP contains much better information to parse.

Parameters:
  • inc_raw – Boolean for whether to include the raw whois results in the returned dictionary.
  • retry_count – The number of times to retry in case socket errors, timeouts, connection resets, etc. are encountered.
  • depth – How many levels deep to run queries when additional referenced objects are found.
  • excluded_entities – A list of entity handles to not perform lookups.
  • bootstrap – If True, performs lookups via ARIN bootstrap rather than lookups based on ASN data. ASN lookups are not performed and no output for any of the asn* fields is provided.
  • rate_limit_timeout – The number of seconds to wait before retrying when a rate limit notice is returned via rdap+json.
  • asn_alts – Array of additional lookup types to attempt if the ASN dns lookup fails. Allow permutations must be enabled. Defaults to all [‘whois’, ‘http’].
  • extra_org_map – Dictionary mapping org handles to RIRs. This is for limited cases where ARIN REST (ASN fallback HTTP lookup) does not show an RIR as the org handle e.g., DNIC (which is now the built in ORG_MAP) e.g., {‘DNIC’: ‘arin’}. Valid RIR values are (note the case-sensitive - this is meant to match the REST result): ‘ARIN’, ‘RIPE’, ‘apnic’, ‘lacnic’, ‘afrinic’
  • inc_nir – Boolean for whether to retrieve NIR (National Internet Registry) information, if registry is JPNIC (Japan) or KRNIC (Korea). If True, extra network requests will be required. If False, the information returned for JP or KR IPs is severely restricted.
  • nir_field_list – If provided and inc_nir, a list of fields to parse: [‘name’, ‘handle’, ‘country’, ‘address’, ‘postal_code’, ‘nameservers’, ‘created’, ‘updated’, ‘contacts’]
Returns:

query:The IP address (String)
asn:The Autonomous System Number (String)
asn_date:The ASN Allocation date (String)
asn_registry:The assigned ASN registry (String)
asn_cidr:The assigned ASN CIDR (String)
asn_country_code:
 The assigned ASN country code (String)
entities:List of entity handles referred by the top level query.
network:Dictionary containing network information which consists of the fields listed in the ipwhois.rdap._RDAPNetwork dict.
objects:Dictionary of (entity handle: entity dict) which consists of the fields listed in the ipwhois.rdap._RDAPEntity dict.
raw:(Dictionary) - Whois results in json format if the inc_raw parameter is True.
nir:(Dictionary) - nir.NIRWhois() results if inc_nir is True.

Return type:

Dictionary

lookup_whois(inc_raw=False, retry_count=3, get_referral=False, extra_blacklist=None, ignore_referral_errors=False, field_list=None, asn_alts=None, extra_org_map=None, inc_nir=True, nir_field_list=None)[source]

The function for retrieving and parsing whois information for an IP address via port 43 (WHOIS).

Parameters:
  • inc_raw – Boolean for whether to include the raw whois results in the returned dictionary.
  • retry_count – The number of times to retry in case socket errors, timeouts, connection resets, etc. are encountered.
  • get_referral – Boolean for whether to retrieve referral whois information, if available.
  • extra_blacklist – A list of blacklisted whois servers in addition to the global BLACKLIST.
  • ignore_referral_errors – Boolean for whether to ignore and continue when an exception is encountered on referral whois lookups.
  • field_list – If provided, a list of fields to parse: [‘name’, ‘handle’, ‘description’, ‘country’, ‘state’, ‘city’, ‘address’, ‘postal_code’, ‘emails’, ‘created’, ‘updated’]
  • asn_alts – Array of additional lookup types to attempt if the ASN dns lookup fails. Allow permutations must be enabled. Defaults to all [‘whois’, ‘http’].
  • extra_org_map – Dictionary mapping org handles to RIRs. This is for limited cases where ARIN REST (ASN fallback HTTP lookup) does not show an RIR as the org handle e.g., DNIC (which is now the built in ORG_MAP) e.g., {‘DNIC’: ‘arin’}. Valid RIR values are (note the case-sensitive - this is meant to match the REST result): ‘ARIN’, ‘RIPE’, ‘apnic’, ‘lacnic’, ‘afrinic’
  • inc_nir – Boolean for whether to retrieve NIR (National Internet Registry) information, if registry is JPNIC (Japan) or KRNIC (Korea). If True, extra network requests will be required. If False, the information returned for JP or KR IPs is severely restricted.
  • nir_field_list – If provided and inc_nir, a list of fields to parse: [‘name’, ‘handle’, ‘country’, ‘address’, ‘postal_code’, ‘nameservers’, ‘created’, ‘updated’, ‘contacts’]
Returns:

query:The IP address (String)
asn:The Autonomous System Number (String)
asn_date:The ASN Allocation date (String)
asn_registry:The assigned ASN registry (String)
asn_cidr:The assigned ASN CIDR (String)
asn_country_code:
 The assigned ASN country code (String)
nets:Dictionaries containing network information which consists of the fields listed in the ipwhois.whois.RIR_WHOIS dictionary. (List)
raw:Raw whois results if the inc_raw parameter is True. (String)
referral:Dictionary of referral whois information if get_referral is True and the server isn’t blacklisted. Consists of fields listed in the ipwhois.whois.RWHOIS dictionary.
raw_referral:Raw referral whois results if the inc_raw parameter is True. (String)
nir:(Dictionary) - nir.NIRWhois() results if inc_nir is True.

Return type:

Dictionary

class ipwhois.net.Net(address, timeout=5, proxy_opener=None, allow_permutations=True)[source]

The class for performing network queries.

Parameters:
  • address – An IPv4 or IPv6 address in string format.
  • timeout – The default timeout for socket connections in seconds.
  • proxy_opener – The urllib.request.OpenerDirector request for proxy support or None.
  • allow_permutations – Use additional methods if DNS lookups to Cymru fail.
Raises:

IPDefinedError – The address provided is defined (does not need to be resolved).

get_asn_dns(result=None)[source]

The function for retrieving ASN information for an IP address from Cymru via port 53 (DNS).

Parameters:

result – Optional result object. This bypasses the ASN lookup.

Returns:

A dictionary containing the following keys:

asn (String) - The Autonomous System Number. asn_date (String) - The ASN Allocation date. asn_registry (String) - The assigned ASN registry. asn_cidr (String) - The assigned ASN CIDR. asn_country_code (String) - The assigned ASN country code.

Return type:

Dictionary

Raises:
  • ASNRegistryError – The ASN registry is not known.
  • ASNLookupError – The ASN lookup failed.
get_asn_http(retry_count=3, result=None, extra_org_map=None)[source]

The function for retrieving ASN information for an IP address from Arin via port 80 (HTTP). Currently limited to fetching asn_registry through a Arin whois (REST) lookup. The other values are returned as None to keep a consistent dict output. This should be used as a last chance fallback call behind ASN DNS & ASN Whois lookups.

Parameters:
  • retry_count – The number of times to retry in case socket errors, timeouts, connection resets, etc. are encountered.
  • result – Optional result object. This bypasses the ASN lookup.
  • extra_org_map – Dictionary mapping org handles to RIRs. This is for limited cases where ARIN REST (ASN fallback HTTP lookup) does not show an RIR as the org handle e.g., DNIC (which is now the built in ORG_MAP) e.g., {‘DNIC’: ‘arin’}. Valid RIR values are (note the case-sensitive - this is meant to match the REST result): ‘ARIN’, ‘RIPE’, ‘apnic’, ‘lacnic’, ‘afrinic’
Returns:

A dictionary containing the following keys:

asn (String) - None, can’t retrieve with this method. asn_date (String) - None, can’t retrieve with this method. asn_registry (String) - The assigned ASN registry. asn_cidr (String) - None, can’t retrieve with this method. asn_country_code (String) - None, can’t retrieve with this method.

Return type:

Dictionary

Raises:
  • ASNRegistryError – The ASN registry is not known.
  • ASNLookupError – The ASN lookup failed.
get_asn_whois(retry_count=3, result=None)[source]

The function for retrieving ASN information for an IP address from Cymru via port 43/tcp (WHOIS).

Parameters:
  • retry_count – The number of times to retry in case socket errors, timeouts, connection resets, etc. are encountered.
  • result – Optional result object. This bypasses the ASN lookup.
Returns:

A dictionary containing the following keys:

asn (String) - The Autonomous System Number. asn_date (String) - The ASN Allocation date. asn_registry (String) - The assigned ASN registry. asn_cidr (String) - The assigned ASN CIDR. asn_country_code (String) - The assigned ASN country code.

Return type:

Dictionary

Raises:
  • ASNRegistryError – The ASN registry is not known.
  • ASNLookupError – The ASN lookup failed.
get_host(retry_count=3)[source]

The function for retrieving host information for an IP address.

Parameters:retry_count – The number of times to retry in case socket errors, timeouts, connection resets, etc. are encountered.
Returns:hostname, aliaslist, ipaddrlist
Return type:Tuple
Raises:HostLookupError – The host lookup failed.
get_http_json(url=None, retry_count=3, rate_limit_timeout=120, headers=None)[source]

The function for retrieving a json result via HTTP.

Parameters:
  • url – The URL to retrieve.
  • retry_count – The number of times to retry in case socket errors, timeouts, connection resets, etc. are encountered.
  • rate_limit_timeout – The number of seconds to wait before retrying when a rate limit notice is returned via rdap+json.
  • headers – The HTTP headers dictionary. The Accept header defaults to ‘application/rdap+json’.
Returns:

The data in json format.

Return type:

Dictionary

Raises:
  • HTTPLookupError – The HTTP lookup failed.
  • HTTPRateLimitError – The HTTP request rate limited and retries were exhausted.
get_http_raw(url=None, retry_count=3, headers=None, request_type='GET', form_data=None)[source]

The function for retrieving a raw HTML result via HTTP.

Parameters:
  • url – The URL to retrieve.
  • retry_count – The number of times to retry in case socket errors, timeouts, connection resets, etc. are encountered.
  • headers – The HTTP headers dictionary. The Accept header defaults to ‘application/rdap+json’.
  • request_type – ‘GET’ or ‘POST’
  • form_data – Dictionary of form POST data
Returns:

The raw data.

Return type:

String

Raises:

HTTPLookupError – The HTTP lookup failed.

get_whois(asn_registry='arin', retry_count=3, server=None, port=43, extra_blacklist=None)[source]

The function for retrieving whois or rwhois information for an IP address via any port. Defaults to port 43/tcp (WHOIS).

Parameters:
  • asn_registry – The NIC to run the query against.
  • retry_count – The number of times to retry in case socket errors, timeouts, connection resets, etc. are encountered.
  • server – An optional server to connect to. If provided, asn_registry will be ignored.
  • port – The network port to connect on.
  • extra_blacklist – A list of blacklisted whois servers in addition to the global BLACKLIST.
Returns:

The raw whois data.

Return type:

String

Raises:
  • BlacklistError – Raised if the whois server provided is in the global BLACKLIST or extra_blacklist.
  • WhoisLookupError – The whois lookup failed.
lookup_asn(retry_count=3, asn_alts=None, extra_org_map=None)[source]

The wrapper function for retrieving and parsing ASN information for an IP address.

Parameters:
  • retry_count – The number of times to retry in case socket errors, timeouts, connection resets, etc. are encountered.
  • asn_alts – Array of additional lookup types to attempt if the ASN dns lookup fails. Allow permutations must be enabled. Defaults to all [‘whois’, ‘http’].
  • extra_org_map – Dictionary mapping org handles to RIRs. This is for limited cases where ARIN REST (ASN fallback HTTP lookup) does not show an RIR as the org handle e.g., DNIC (which is now the built in ORG_MAP) e.g., {‘DNIC’: ‘arin’}. Valid RIR values are (note the case-sensitive - this is meant to match the REST result): ‘ARIN’, ‘RIPE’, ‘apnic’, ‘lacnic’, ‘afrinic’
Returns:

Dictionary:Result from get_asn_dns() or get_asn_whois().
Dictionary:The response returned by get_asn_dns() or get_asn_whois().

Return type:

Tuple

Raises:
  • ASNRegistryError – ASN registry does not match.
  • HTTPLookupError – The HTTP lookup failed.
class ipwhois.rdap.RDAP(net)[source]

The class for parsing IP address whois information via RDAP: https://tools.ietf.org/html/rfc7483 https://www.arin.net/resources/rdap.html

Parameters:

net – A ipwhois.net.Net object.

Raises:
  • NetError – The parameter provided is not an instance of ipwhois.net.Net
  • IPDefinedError – The address provided is defined (does not need to be resolved).
lookup(inc_raw=False, retry_count=3, asn_data=None, depth=0, excluded_entities=None, response=None, bootstrap=False, rate_limit_timeout=120)[source]

The function for retrieving and parsing information for an IP address via RDAP (HTTP).

Parameters:
  • inc_raw – Boolean for whether to include the raw results in the returned dictionary.
  • retry_count – The number of times to retry in case socket errors, timeouts, connection resets, etc. are encountered.
  • asn_data – Result dictionary from ipwhois.net.Net.lookup_asn(). Optional if the bootstrap parameter is True.
  • depth – How many levels deep to run queries when additional referenced objects are found.
  • excluded_entities – A list of entity handles to not perform lookups.
  • response – Optional response object, this bypasses the RDAP lookup.
  • bootstrap – If True, performs lookups via ARIN bootstrap rather than lookups based on ASN data.
  • rate_limit_timeout – The number of seconds to wait before retrying when a rate limit notice is returned via rdap+json.
Returns:

query:The IP address (String)
network:Dictionary of values returned by _RDAPNetwork. The raw result is included for each entity if the inc_raw parameter is True.
entities:List of entity keys referenced by the top level IP address query.
objects:Dictionary of objects with the handles as keys, and the dictionary returned by _RDAPEntity, etc as the values. The raw result is included for each object if the inc_raw parameter is True.

Return type:

Dictionary

class ipwhois.whois.Whois(net)[source]

The class for parsing via whois

Parameters:

net – A ipwhois.net.Net object.

Raises:
  • NetError – The parameter provided is not an instance of ipwhois.net.Net
  • IPDefinedError – The address provided is defined (does not need to be resolved).
lookup(inc_raw=False, retry_count=3, response=None, get_referral=False, extra_blacklist=None, ignore_referral_errors=False, asn_data=None, field_list=None, is_offline=False)[source]

The function for retrieving and parsing whois information for an IP address via port 43/tcp (WHOIS).

Parameters:
  • inc_raw – Boolean for whether to include the raw results in the returned dictionary.
  • retry_count – The number of times to retry in case socket errors, timeouts, connection resets, etc. are encountered.
  • response – Optional response object, this bypasses the Whois lookup.
  • get_referral – Boolean for whether to retrieve referral whois information, if available.
  • extra_blacklist – A list of blacklisted whois servers in addition to the global BLACKLIST.
  • ignore_referral_errors – Boolean for whether to ignore and continue when an exception is encountered on referral whois lookups.
  • asn_data – Optional ASN result object, this bypasses the ASN lookup.
  • field_list – If provided, a list of fields to parse: [‘name’, ‘handle’, ‘description’, ‘country’, ‘state’, ‘city’, ‘address’, ‘postal_code’, ‘emails’, ‘created’, ‘updated’]
  • is_offline – Boolean for whether to perform lookups offline. If True, response and asn_data must be provided. Primarily used for testing.
Returns:

query:The IP address (String)
asn:The Autonomous System Number (String)
asn_date:The ASN Allocation date (String)
asn_registry:The assigned ASN registry (String)
asn_cidr:The assigned ASN CIDR (String)
asn_country_code:
 The assigned ASN country code (String)
nets:Dictionaries containing network information which consists of the fields listed in the NIC_WHOIS dictionary. (List)
raw:Raw whois results if the inc_raw parameter is True. (String)
referral:Dictionary of referral whois information if get_referral is True and the server isn’t blacklisted. Consists of fields listed in the RWHOIS dictionary.
raw_referral:Raw referral whois results if the inc_raw parameter is True. (String)

Return type:

Dictionary

class ipwhois.nir.NIRWhois(net)[source]

The class for parsing whois data for NIRs (National Internet Registry). JPNIC and KRNIC are currently the only NIRs supported. Output varies based on NIR specific whois formatting.

Parameters:

net – A ipwhois.net.Net object.

Raises:
  • NetError – The parameter provided is not an instance of ipwhois.net.Net
  • IPDefinedError – The address provided is defined (does not need to be resolved).
lookup(nir=None, inc_raw=False, retry_count=3, response=None, field_list=None, is_offline=False)[source]

The function for retrieving and parsing NIR whois information for an IP address via HTTP (HTML scraping).

Parameters:
  • nir – The NIR to query (‘jpnic’ or ‘krnic’).
  • inc_raw – Boolean for whether to include the raw results in the returned dictionary.
  • retry_count – The number of times to retry in case socket errors, timeouts, connection resets, etc. are encountered.
  • response – Optional response object, this bypasses the NIR lookup.
  • field_list – If provided, a list of fields to parse: [‘name’, ‘handle’, ‘country’, ‘address’, ‘postal_code’, ‘nameservers’, ‘created’, ‘updated’, ‘contacts’]
  • is_offline – Boolean for whether to perform lookups offline. If True, response and asn_data must be provided. Primarily used for testing.
Returns:

query:The IP address (String)
nets:List of dictionaries containing network information which consists of the fields listed in the NIR_WHOIS dictionary.
raw:Raw NIR whois results if the inc_raw parameter is True. (String)

Return type:

Dictionary

ipwhois.utils.calculate_cidr(start_address, end_address)[source]

The function to calculate a CIDR range(s) from a start and end IP address.

Parameters:
  • start_address – The starting IP address in string format.
  • end_address – The ending IP address in string format.
Returns:

A list of calculated CIDR ranges.

Return type:

List

ipwhois.utils.get_countries(is_legacy_xml=False)[source]

The function to generate a dictionary containing ISO_3166-1 country codes to names.

Parameters:is_legacy_xml – Boolean for whether to use the older country code list (iso_3166-1_list_en.xml).
Returns:
A dictionary with the country codes as the keys and the
country names as the values.
Return type:Dictionary
ipwhois.utils.ipv4_is_defined(address)[source]

The function for checking if an IPv4 address is defined (does not need to be resolved).

Parameters:address – An IPv4 address in string format.
Returns:
Boolean:True if given address is defined, otherwise False
String:IETF assignment name if given address is defined, otherwise ‘’
String:IETF assignment RFC if given address is defined, otherwise ‘’
Return type:Tuple
ipwhois.utils.ipv4_lstrip_zeros(address)[source]

The function to strip leading zeros in each octet of an IPv4 address.

Parameters:address – An IPv4 address in string format.
Returns:The modified IPv4 address string.
Return type:String
ipwhois.utils.ipv6_is_defined(address)[source]

The function for checking if an IPv6 address is defined (does not need to be resolved).

Parameters:address – An IPv6 address in string format.
Returns:
Boolean:True if address is defined, otherwise False
String:IETF assignment name if address is defined, otherwise ‘’
String:IETF assignment RFC if address is defined, otherwise ‘’
Return type:Tuple
ipwhois.utils.unique_addresses(data=None, file_path=None)[source]

The function to search an input string and/or file, extracting and counting IPv4/IPv6 addresses/networks. Summarizes ports with sub-counts. If both a string and file_path are provided, it will process them both.

Parameters:
  • data – A string to process.
  • file_path – An optional file path to process.
Returns:

ip address/network:
 

Each address or network found is a dictionary w/:

count:Total number of times seen (Integer)
ports:Dictionary with port numbers as keys and the number of times seen for this ip as values (Dictionary)

Return type:

Dictionary

Raises:

ValueError – Arguments provided are invalid.

ipwhois.utils.unique_everseen(iterable, key=None)[source]

The generator to list unique elements, preserving the order. Remember all elements ever seen. This was taken from the itertools recipes.

Parameters:
  • iterable – An iterable to process.
  • key – Optional function to run when checking elements (e.g., str.lower)
Returns:

Yields a generator object.

Return type:

Generator

exception ipwhois.exceptions.ASNLookupError[source]

An Exception for when the ASN lookup failed.

exception ipwhois.exceptions.ASNRegistryError[source]

An Exception for when the ASN registry does not match one of the five expected values (arin, ripencc, apnic, lacnic, afrinic).

exception ipwhois.exceptions.BlacklistError[source]

An Exception for when the server is in a blacklist.

exception ipwhois.exceptions.HTTPLookupError[source]

An Exception for when the RDAP lookup failed.

exception ipwhois.exceptions.HTTPRateLimitError[source]

An Exception for when HTTP queries exceed the NIC’s request limit and have exhausted all retries.

exception ipwhois.exceptions.HostLookupError[source]

An Exception for when the host lookup failed.

exception ipwhois.exceptions.IPDefinedError[source]

An Exception for when the IP is defined (does not need to be resolved).

exception ipwhois.exceptions.InvalidEntityContactObject[source]

An Exception for when JSON output is not an RDAP entity contact information object: https://tools.ietf.org/html/rfc7483#section-5.4

exception ipwhois.exceptions.InvalidEntityObject[source]

An Exception for when JSON output is not an RDAP entity object: https://tools.ietf.org/html/rfc7483#section-5.1

exception ipwhois.exceptions.InvalidNetworkObject[source]

An Exception for when JSON output is not an RDAP network object: https://tools.ietf.org/html/rfc7483#section-5.4

exception ipwhois.exceptions.NetError[source]

An Exception for when a parameter provided is not an instance of ipwhois.net.Net.

exception ipwhois.exceptions.WhoisLookupError[source]

An Exception for when the whois lookup failed.