Library Structure

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

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

Parameters:
  • address (str/int/IPv4Address/IPv6Address) – An IPv4 or IPv6 address
  • timeout (int) – The default timeout for socket connections in seconds. Defaults to 5.
  • proxy_opener (urllib.request.OpenerDirector) – The request for proxy support. Defaults to None.
  • allow_permutations (bool) – Allow net.Net() to use additional methods if DNS lookups to Cymru fail. WARNING deprecated in favor of new argument asn_methods. Defaults to False.
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, asn_methods=None, get_asn_description=True)[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 (bool) – Whether to include the raw whois results in the returned dictionary. Defaults to False.
  • retry_count (int) – The number of times to retry in case socket errors, timeouts, connection resets, etc. are encountered. Defaults to 3.
  • depth (int) – How many levels deep to run queries when additional referenced objects are found. Defaults to 0.
  • excluded_entities (list) – Entity handles to not perform lookups. Defaults to None.
  • bootstrap (bool) – 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. Defaults to False.
  • rate_limit_timeout (int) – The number of seconds to wait before retrying when a rate limit notice is returned via rdap+json. Defaults to 120.
  • asn_alts (list) – Additional lookup types to attempt if the ASN dns lookup fails. Allow permutations must be enabled. If None, defaults to all [‘whois’, ‘http’]. WARNING deprecated in favor of new argument asn_methods.
  • extra_org_map (dict) – 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’ Defaults to None.
  • inc_nir (bool) – 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. Defaults to True.
  • nir_field_list (list) – If provided and inc_nir, a list of fields to parse: [‘name’, ‘handle’, ‘country’, ‘address’, ‘postal_code’, ‘nameservers’, ‘created’, ‘updated’, ‘contacts’] If None, defaults to all.
  • asn_methods (list) – ASN lookup types to attempt, in order. If None, defaults to all [‘dns’, ‘whois’, ‘http’].
  • get_asn_description (bool) – Whether to run an additional query when pulling ASN information via dns, in order to get the ASN description. Defaults to True.
Returns:

The IP RDAP lookup results

{
    'query' (str) - The IP address
    'asn' (str) - The Autonomous System Number
    'asn_date' (str) - The ASN Allocation date
    'asn_registry' (str) - The assigned ASN registry
    'asn_cidr' (str) - The assigned ASN CIDR
    'asn_country_code' (str) - The assigned ASN country code
    'asn_description' (str) - The ASN description
    'entities' (list) - Entity handles referred by the top
        level query.
    'network' (dict) - Network information which consists of
        the fields listed in the ipwhois.rdap._RDAPNetwork
        dict.
    'objects' (dict) - Mapping of entity handle->entity dict
        which consists of the fields listed in the
        ipwhois.rdap._RDAPEntity dict. The raw result is
        included for each object if the inc_raw parameter
        is True.
    'raw' (dict) - Whois results in json format if the inc_raw
        parameter is True.
    'nir' (dict) - ipwhois.nir.NIRWhois results if inc_nir is
        True.
}

Return type:

dict

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, asn_methods=None, get_asn_description=True)[source]

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

Parameters:
  • inc_raw (bool) – Whether to include the raw whois results in the returned dictionary. Defaults to False.
  • retry_count (int) – The number of times to retry in case socket errors, timeouts, connection resets, etc. are encountered. Defaults to 3.
  • get_referral (bool) – Whether to retrieve referral whois information, if available. Defaults to False.
  • extra_blacklist (list) – Blacklisted whois servers in addition to the global BLACKLIST. Defaults to None.
  • ignore_referral_errors (bool) – Whether to ignore and continue when an exception is encountered on referral whois lookups. Defaults to False.
  • field_list (list) – If provided, a list of fields to parse: [‘name’, ‘handle’, ‘description’, ‘country’, ‘state’, ‘city’, ‘address’, ‘postal_code’, ‘emails’, ‘created’, ‘updated’] If None, defaults to all.
  • asn_alts (list) – Additional lookup types to attempt if the ASN dns lookup fails. Allow permutations must be enabled. If None, defaults to all [‘whois’, ‘http’]. WARNING deprecated in favor of new argument asn_methods.
  • extra_org_map (dict) – 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’ Defaults to None.
  • inc_nir (bool) – 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. Defaults to True.
  • nir_field_list (list) – If provided and inc_nir, a list of fields to parse: [‘name’, ‘handle’, ‘country’, ‘address’, ‘postal_code’, ‘nameservers’, ‘created’, ‘updated’, ‘contacts’] If None, defaults to all.
  • asn_methods (list) – ASN lookup types to attempt, in order. If None, defaults to all [‘dns’, ‘whois’, ‘http’].
  • get_asn_description (bool) – Whether to run an additional query when pulling ASN information via dns, in order to get the ASN description. Defaults to True.
Returns:

The IP whois lookup results

{
    'query' (str) - The IP address
    'asn' (str) - The Autonomous System Number
    'asn_date' (str) - The ASN Allocation date
    'asn_registry' (str) - The assigned ASN registry
    'asn_cidr' (str) - The assigned ASN CIDR
    'asn_country_code' (str) - The assigned ASN country code
    'asn_description' (str) - The ASN description
    'nets' (list) - Dictionaries containing network
        information which consists of the fields listed in the
        ipwhois.whois.RIR_WHOIS dictionary.
    'raw' (str) - Raw whois results if the inc_raw parameter
        is True.
    'referral' (dict) - Referral whois information if
        get_referral is True and the server is not blacklisted.
        Consists of fields listed in the ipwhois.whois.RWHOIS
        dictionary.
    'raw_referral' (str) - Raw referral whois results if the
        inc_raw parameter is True.
    'nir' (dict) - ipwhois.nir.NIRWhois() results if inc_nir
        is True.
}

Return type:

dict

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

The class for performing network queries.

Parameters:
  • address (str/int/IPv4Address/IPv6Address) – An IPv4 or IPv6 address
  • timeout (int) – The default timeout for socket connections in seconds. Defaults to 5.
  • proxy_opener (urllib.request.OpenerDirector) – The request for proxy support. Defaults to None.
  • allow_permutations (bool) – Allow net.Net() to use additional methods if DNS lookups to Cymru fail. WARNING deprecated in favor of new argument asn_methods. Defaults to False.
Raises:

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

get_asn_dns()[source]

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

Returns:The raw ASN data.
Return type:list
Raises:ASNLookupError – The ASN lookup failed.
get_asn_http(retry_count=3)[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 (int) – The number of times to retry in case socket errors, timeouts, connection resets, etc. are encountered. Defaults to 3.
Returns:The ASN data in json format.
Return type:dict
Raises:ASNLookupError – The ASN lookup failed.
get_asn_origin_whois(asn_registry='radb', asn=None, retry_count=3, server=None, port=43)[source]

The function for retrieving CIDR info for an ASN via whois.

Parameters:
  • asn_registry (str) – The source to run the query against (asn.ASN_ORIGIN_WHOIS).
  • asn (str) – The AS number (required).
  • retry_count (int) – The number of times to retry in case socket errors, timeouts, connection resets, etc. are encountered. Defaults to 3.
  • server (str) – An optional server to connect to.
  • port (int) – The network port to connect on. Defaults to 43.
Returns:

The raw ASN origin whois data.

Return type:

str

Raises:
get_asn_verbose_dns(asn=None)[source]

The function for retrieving the information for an ASN from Cymru via port 53 (DNS). This is needed since IP to ASN mapping via Cymru DNS does not return the ASN Description like Cymru Whois does.

Parameters:asn (str) – The AS number (required).
Returns:The raw ASN data.
Return type:str
Raises:ASNLookupError – The ASN lookup failed.
get_asn_whois(retry_count=3)[source]

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

Parameters:retry_count (int) – The number of times to retry in case socket errors, timeouts, connection resets, etc. are encountered. Defaults to 3.
Returns:The raw ASN data.
Return type:str
Raises:ASNLookupError – The ASN lookup failed.
get_host(retry_count=3)[source]

The function for retrieving host information for an IP address.

Parameters:retry_count (int) – The number of times to retry in case socket errors, timeouts, connection resets, etc. are encountered. Defaults to 3.
Returns:
hostname (str):The hostname returned mapped to the given IP address.
aliaslist (list):
 Alternate names for the given IP address.
ipaddrlist (list):
 IPv4/v6 addresses mapped to the same hostname.
Return type:namedtuple
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 (str) – The URL to retrieve (required).
  • retry_count (int) – The number of times to retry in case socket errors, timeouts, connection resets, etc. are encountered. Defaults to 3.
  • rate_limit_timeout (int) – The number of seconds to wait before retrying when a rate limit notice is returned via rdap+json or HTTP error 429. Defaults to 60.
  • headers (dict) – The HTTP headers. The Accept header defaults to ‘application/rdap+json’.
Returns:

The data in json format.

Return type:

dict

Raises:
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 (str) – The URL to retrieve (required).
  • retry_count (int) – The number of times to retry in case socket errors, timeouts, connection resets, etc. are encountered. Defaults to 3.
  • headers (dict) – The HTTP headers. The Accept header defaults to ‘text/html’.
  • request_type (str) – Request type ‘GET’ or ‘POST’. Defaults to ‘GET’.
  • form_data (dict) – Optional form POST data.
Returns:

The raw data.

Return type:

str

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 (str) – The NIC to run the query against. Defaults to ‘arin’.
  • retry_count (int) – The number of times to retry in case socket errors, timeouts, connection resets, etc. are encountered. Defaults to 3.
  • server (str) – An optional server to connect to. If provided, asn_registry will be ignored.
  • port (int) – The network port to connect on. Defaults to 43.
  • extra_blacklist (list of str) – Blacklisted whois servers in addition to the global BLACKLIST. Defaults to None.
Returns:

The raw whois data.

Return type:

str

Raises:
lookup_asn(*args, **kwargs)[source]

Temporary wrapper for IP ASN lookups (moved to asn.IPASN.lookup()). This will be removed in a future release.

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 (ipwhois.net.Net) – The network 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 (bool, optional) – Whether to include the raw results in the returned dictionary. Defaults to False.
  • retry_count (int) – The number of times to retry in case socket errors, timeouts, connection resets, etc. are encountered. Defaults to 3.
  • asn_data (dict) – Result from ipwhois.asn.IPASN.lookup. Optional if the bootstrap parameter is True.
  • depth (int) – How many levels deep to run queries when additional referenced objects are found. Defaults to 0.
  • excluded_entities (list) – Entity handles to not perform lookups. Defaults to None.
  • response (str) – Optional response object, this bypasses the RDAP lookup.
  • bootstrap (bool) – If True, performs lookups via ARIN bootstrap rather than lookups based on ASN data. Defaults to False.
  • rate_limit_timeout (int) – The number of seconds to wait before retrying when a rate limit notice is returned via rdap+json. Defaults to 120.
Returns:

The IP RDAP lookup results

{
    'query' (str) - The IP address
    'entities' (list) - Entity handles referred by the top
        level query.
    'network' (dict) - Network information which consists of
        the fields listed in the ipwhois.rdap._RDAPNetwork
        dict.
    'objects' (dict) - Mapping of entity handle->entity dict
        which consists of the fields listed in the
        ipwhois.rdap._RDAPEntity dict. The raw result is
        included for each object if the inc_raw parameter
        is True.
}

Return type:

dict

class ipwhois.rdap._RDAPCommon(json_result)[source]

The common class for parsing RDAP objects: https://tools.ietf.org/html/rfc7483#section-5

Parameters:json_result (dict) – The JSON response from an RDAP query.
Raises:ValueError – vcard is not a known RDAP object.
_parse()[source]

The function for parsing the JSON response to the vars dictionary.

summarize_events(events_json)[source]

The function for summarizing RDAP events in to a unique list. https://tools.ietf.org/html/rfc7483#section-4.5

Parameters:events_json (dict) – A json mapping of events from RDAP results.
Returns:Unique RDAP events information:
 [{
     'action' (str) - The reason for an event.
     'timestamp' (str) - The timestamp for when an event
         occured.
     'actor' (str) - The identifier for an event initiator.
}]
Return type:list of dict

The function for summarizing RDAP links in to a unique list. https://tools.ietf.org/html/rfc7483#section-4.2

Parameters:links_json (dict) – A json mapping of links from RDAP results.
Returns:Unique RDAP links.
Return type:list of str
summarize_notices(notices_json)[source]

The function for summarizing RDAP notices in to a unique list. https://tools.ietf.org/html/rfc7483#section-4.3

Parameters:notices_json (dict) – A json mapping of notices from RDAP results.
Returns:Unique RDAP notices information:
 [{
     'title' (str) - The title/header of the notice.
     'description' (str) - The description/body of the notice.
     'links' (list) - Unique links returned by
         :obj:`ipwhois.rdap._RDAPCommon.summarize_links()`.
}]
Return type:list of dict
class ipwhois.rdap._RDAPContact(vcard)[source]

The class for parsing RDAP entity contact information objects: https://tools.ietf.org/html/rfc7483#section-5.1 https://tools.ietf.org/html/rfc7095

Parameters:vcard (list of list) – The vcard list from an RDAP IP address query.
Raises:InvalidEntityContactObject – vcard is not an RDAP entity contact information object.
_parse_address(val)[source]

The function for parsing the vcard address.

Parameters:val (list) – The value to parse.
_parse_email(val)[source]

The function for parsing the vcard email addresses.

Parameters:val (list) – The value to parse.
_parse_kind(val)[source]

The function for parsing the vcard kind.

Parameters:val (list) – The value to parse.
_parse_name(val)[source]

The function for parsing the vcard name.

Parameters:val (list) – The value to parse.
_parse_phone(val)[source]

The function for parsing the vcard phone numbers.

Parameters:val (list) – The value to parse.
_parse_role(val)[source]

The function for parsing the vcard role.

Parameters:val (list) – The value to parse.
_parse_title(val)[source]

The function for parsing the vcard title.

Parameters:val (list) – The value to parse.
parse()[source]

The function for parsing the vcard to the vars dictionary.

class ipwhois.rdap._RDAPEntity(json_result)[source]

The class for parsing RDAP entity objects: https://tools.ietf.org/html/rfc7483#section-5.1

Parameters:json_result (dict) – The JSON response from an RDAP query.
Raises:InvalidEntityObject – json_result is not an RDAP entity object.
parse()[source]

The function for parsing the JSON response to the vars dictionary.

class ipwhois.rdap._RDAPNetwork(json_result)[source]

The class for parsing RDAP network objects: https://tools.ietf.org/html/rfc7483#section-5.4

Parameters:json_result (dict) – The JSON response from an RDAP IP address query.
Raises:InvalidNetworkObject – json_result is not an RDAP network object.
parse()[source]

The function for parsing the JSON response to the vars dictionary.

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

The class for parsing via whois

Parameters:

net (ipwhois.net.Net) – The network 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).
_get_nets_arin(*args, **kwargs)[source]

Deprecated. This will be removed in a future release.

_get_nets_lacnic(*args, **kwargs)[source]

Deprecated. This will be removed in a future release.

_get_nets_other(*args, **kwargs)[source]

Deprecated. This will be removed in a future release.

_parse_fields(*args, **kwargs)[source]

Deprecated. This will be removed in a future release.

get_nets_arin(response)[source]

The function for parsing network blocks from ARIN whois data.

Parameters:response (str) – The response from the ARIN whois server.
Returns:Mapping of networks with start and end positions.
[{
    'cidr' (str) - The network routing block
    'start' (int) - The starting point of the network
    'end' (int) - The endpoint point of the network
}]
Return type:list of dict
get_nets_lacnic(response)[source]

The function for parsing network blocks from LACNIC whois data.

Parameters:response (str) – The response from the LACNIC whois server.
Returns:Mapping of networks with start and end positions.
[{
    'cidr' (str) - The network routing block
    'start' (int) - The starting point of the network
    'end' (int) - The endpoint point of the network
}]
Return type:list of dict
get_nets_other(response)[source]

The function for parsing network blocks from generic whois data.

Parameters:response (str) – The response from the whois/rwhois server.
Returns:Mapping of networks with start and end positions.
[{
    'cidr' (str) - The network routing block
    'start' (int) - The starting point of the network
    'end' (int) - The endpoint point of the network
}]
Return type:list of dict
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 (bool, optional) – Whether to include the raw results in the returned dictionary. Defaults to False.
  • retry_count (int) – The number of times to retry in case socket errors, timeouts, connection resets, etc. are encountered. Defaults to 3.
  • response (str) – Optional response object, this bypasses the NIR lookup. Required when is_offline=True.
  • get_referral (bool) – Whether to retrieve referral whois information, if available. Defaults to False.
  • extra_blacklist (list) – Blacklisted whois servers in addition to the global BLACKLIST. Defaults to None.
  • ignore_referral_errors (bool) – Whether to ignore and continue when an exception is encountered on referral whois lookups. Defaults to False.
  • asn_data (dict) – Result from ipwhois.asn.IPASN.lookup (required).
  • field_list (list of str) –

    If provided, fields to parse. Defaults to:

    ['name', 'handle', 'description', 'country', 'state',
    'city', 'address', 'postal_code', 'emails', 'created',
    'updated']
    
  • is_offline (bool) – Whether to perform lookups offline. If True, response and asn_data must be provided. Primarily used for testing. Defaults to False.
Returns:

The IP whois lookup results

{
    'query' (str) - The IP address
    'asn' (str) - The Autonomous System Number
    'asn_date' (str) - The ASN Allocation date
    'asn_registry' (str) - The assigned ASN registry
    'asn_cidr' (str) - The assigned ASN CIDR
    'asn_country_code' (str) - The assigned ASN country code
    'asn_description' (str) - The ASN description
    'nets' (list) - Dictionaries containing network
        information which consists of the fields listed in the
        ipwhois.whois.RIR_WHOIS dictionary.
    'raw' (str) - Raw whois results if the inc_raw parameter
        is True.
    'referral' (dict) - Referral whois information if
        get_referral is True and the server is not blacklisted.
        Consists of fields listed in the ipwhois.whois.RWHOIS
        dictionary.
    'raw_referral' (str) - Raw referral whois results if the
        inc_raw parameter is True.
}

Return type:

dict

parse_fields(response, fields_dict, net_start=None, net_end=None, dt_format=None, field_list=None)[source]

The function for parsing whois fields from a data input.

Parameters:
  • response (str) – The response from the whois/rwhois server.
  • fields_dict (dict) – The mapping of fields to regex search values (required).
  • net_start (int) – The starting point of the network (if parsing multiple networks). Defaults to None.
  • net_end (int) – The ending point of the network (if parsing multiple networks). Defaults to None.
  • dt_format (str) – The format of datetime fields if known. Defaults to None.
  • field_list (list of str) –

    If provided, fields to parse. Defaults to:

    ['name', 'handle', 'description', 'country', 'state',
    'city', 'address', 'postal_code', 'emails', 'created',
    'updated']
    
Returns:

A dictionary of fields provided in fields_dict, mapping to

the results of the regex searches.

Return type:

dict

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 (ipwhois.net.Net) – The network 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).
_get_contact(*args, **kwargs)[source]

Deprecated. This will be removed in a future release.

_get_nets_jpnic(*args, **kwargs)[source]

Deprecated. This will be removed in a future release.

_get_nets_krnic(*args, **kwargs)[source]

Deprecated. This will be removed in a future release.

_parse_fields(*args, **kwargs)[source]

Deprecated. This will be removed in a future release.

get_contact(response=None, nir=None, handle=None, retry_count=3, dt_format=None)[source]

The function for retrieving and parsing NIR whois data based on NIR_WHOIS contact_fields.

Parameters:
  • response (str) – Optional response object, this bypasses the lookup.
  • nir (str) – The NIR to query (‘jpnic’ or ‘krnic’). Required if response is None.
  • handle (str) – For NIRs that have separate contact queries (JPNIC), this is the contact handle to use in the query. Defaults to None.
  • retry_count (int) – The number of times to retry in case socket errors, timeouts, connection resets, etc. are encountered. Defaults to 3.
  • dt_format (str) – The format of datetime fields if known. Defaults to None.
Returns:

Mapping of the fields provided in contact_fields, to their

parsed results.

Return type:

dict

get_nets_jpnic(response)[source]

The function for parsing network blocks from jpnic whois data.

Parameters:response (str) – The response from the jpnic server.
Returns:Mapping of networks with start and end positions.
[{
    'cidr' (str) - The network routing block
    'start' (int) - The starting point of the network
    'end' (int) - The endpoint point of the network
}]
Return type:list of dict
get_nets_krnic(response)[source]

The function for parsing network blocks from krnic whois data.

Parameters:response (str) – The response from the krnic server.
Returns:Mapping of networks with start and end positions.
[{
    'cidr' (str) - The network routing block
    'start' (int) - The starting point of the network
    'end' (int) - The endpoint point of the network
}]
Return type:list of dict
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 (str) – The NIR to query (‘jpnic’ or ‘krnic’). Required if response is None.
  • inc_raw (bool, optional) – Whether to include the raw results in the returned dictionary. Defaults to False.
  • retry_count (int) – The number of times to retry in case socket errors, timeouts, connection resets, etc. are encountered. Defaults to 3.
  • response (str) – Optional response object, this bypasses the NIR lookup. Required when is_offline=True.
  • field_list (list of str) – If provided, fields to parse. Defaults to ipwhois.nir.BASE_NET.
  • is_offline (bool) – Whether to perform lookups offline. If True, response and asn_data must be provided. Primarily used for testing.
Returns:

The NIR whois results:

{
    'query' (str) - The IP address.
    'nets' (list of dict) - Network information which consists
        of the fields listed in the ipwhois.nir.NIR_WHOIS
        dictionary.
    'raw' (str) - Raw NIR whois results if the inc_raw
        parameter is True.
}

Return type:

dict

parse_fields(response, fields_dict, net_start=None, net_end=None, dt_format=None, field_list=None, hourdelta=0, is_contact=False)[source]

The function for parsing whois fields from a data input.

Parameters:
  • response (str) – The response from the whois/rwhois server.
  • fields_dict (dict) – The mapping of fields to regex search values (required).
  • net_start (int) – The starting point of the network (if parsing multiple networks). Defaults to None.
  • net_end (int) – The ending point of the network (if parsing multiple networks). Defaults to None.
  • dt_format (str) – The format of datetime fields if known. Defaults to None.
  • field_list (list of str) – If provided, fields to parse. Defaults to ipwhois.nir.BASE_NET if is_contact is False. Otherwise, defaults to ipwhois.nir.BASE_CONTACT.
  • hourdelta (int) – The timezone delta for created/updated fields. Defaults to 0.
  • is_contact (bool) – If True, uses contact information field parsing. Defaults to False.
Returns:

A dictionary of fields provided in fields_dict, mapping to

the results of the regex searches.

Return type:

dict

class ipwhois.asn.ASNOrigin(net)[source]

The class for parsing ASN origin whois data

Parameters:net (ipwhois.net.Net) – A ipwhois.net.Net object.
Raises:NetError – The parameter provided is not an instance of ipwhois.net.Net
_get_nets_radb(*args, **kwargs)[source]

Deprecated. This will be removed in a future release.

_parse_fields(*args, **kwargs)[source]

Deprecated. This will be removed in a future release.

get_nets_radb(response, is_http=False)[source]

The function for parsing network blocks from ASN origin data.

Parameters:
  • response (str) – The response from the RADB whois/http server.
  • is_http (bool) – If the query is RADB HTTP instead of whois, set to True. Defaults to False.
Returns:

A list of network block dictionaries

[{
    'cidr' (str) - The assigned CIDR
    'start' (int) - The index for the start of the parsed
        network block
    'end' (int) - The index for the end of the parsed network
        block
}]

Return type:

list

lookup(asn=None, inc_raw=False, retry_count=3, response=None, field_list=None, asn_alts=None, asn_methods=None)[source]

The function for retrieving and parsing ASN origin whois information via port 43/tcp (WHOIS).

Parameters:
  • asn (str) – The ASN (required).
  • inc_raw (bool) – Whether to include the raw results in the returned dictionary. Defaults to False.
  • retry_count (int) – The number of times to retry in case socket errors, timeouts, connection resets, etc. are encountered. Defaults to 3.
  • response (str) – Optional response object, this bypasses the Whois lookup. Defaults to None.
  • field_list (list) – If provided, fields to parse: [‘description’, ‘maintainer’, ‘updated’, ‘source’] If None, defaults to all.
  • asn_alts (list) – Additional lookup types to attempt if the ASN whois lookup fails. If None, defaults to all [‘http’]. WARNING deprecated in favor of new argument asn_methods.
  • asn_methods (list) – ASN lookup types to attempt, in order. If None, defaults to all [‘whois’, ‘http’].
Returns:

The ASN origin lookup results

{
    'query' (str) - The Autonomous System Number
    'nets' (list) - Dictionaries containing network
        information which consists of the fields listed in the
        ASN_ORIGIN_WHOIS dictionary.
    'raw' (str) - Raw ASN origin whois results if the inc_raw
        parameter is True.
}

Return type:

dict

Raises:
  • ValueError – methods argument requires one of whois, http.
  • ASNOriginLookupError – ASN origin lookup failed.
parse_fields(response, fields_dict, net_start=None, net_end=None, field_list=None)[source]

The function for parsing ASN whois fields from a data input.

Parameters:
  • response (str) – The response from the whois/rwhois server.
  • fields_dict (dict) – Mapping of fields->regex search values.
  • net_start (int) – The starting point of the network (if parsing multiple networks). Defaults to None.
  • net_end (int) – The ending point of the network (if parsing multiple networks). Defaults to None.
  • field_list (list) – If provided, a list of fields to parse: [‘description’, ‘maintainer’, ‘updated’, ‘source’] If None, defaults to all fields.
Returns:

A dictionary of fields provided in fields_dict.

Return type:

dict

class ipwhois.asn.IPASN(net)[source]

The class for parsing ASN data for an IP address.

Parameters:net (ipwhois.net.Net) – A ipwhois.net.Net object.
Raises:NetError – The parameter provided is not an instance of ipwhois.net.Net
_parse_fields_dns(*args, **kwargs)[source]

Deprecated. This will be removed in a future release.

_parse_fields_http(*args, **kwargs)[source]

Deprecated. This will be removed in a future release.

_parse_fields_whois(*args, **kwargs)[source]

Deprecated. This will be removed in a future release.

lookup(inc_raw=False, retry_count=3, asn_alts=None, extra_org_map=None, asn_methods=None, get_asn_description=True)[source]

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

Parameters:
  • inc_raw (bool) – Whether to include the raw results in the returned dictionary. Defaults to False.
  • retry_count (int) – The number of times to retry in case socket errors, timeouts, connection resets, etc. are encountered. Defaults to 3.
  • asn_alts (list) – Additional lookup types to attempt if the ASN dns lookup fails. Allow permutations must be enabled. Defaults to all [‘whois’, ‘http’]. WARNING deprecated in favor of new argument asn_methods. Defaults to None.
  • extra_org_map (dict) – 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’ Defaults to None.
  • asn_methods (list) – ASN lookup types to attempt, in order. If None, defaults to all: [‘dns’, ‘whois’, ‘http’].
  • get_asn_description (bool) – Whether to run an additional query when pulling ASN information via dns, in order to get the ASN description. Defaults to True.
Returns:

The ASN lookup results

{
    'asn' (str) - The Autonomous System Number
    'asn_date' (str) - The ASN Allocation date
    'asn_registry' (str) - The assigned ASN registry
    'asn_cidr' (str) - The assigned ASN CIDR
    'asn_country_code' (str) - The assigned ASN country code
    'asn_description' (str) - The ASN description
    'raw' (str) - Raw ASN results if the inc_raw parameter is
        True.
}

Return type:

dict

Raises:
  • ValueError – methods argument requires one of dns, whois, http.
  • ASNRegistryError – ASN registry does not match.
parse_fields_dns(response)[source]

The function for parsing ASN fields from a dns response.

Parameters:

response (str) – The response from the ASN dns server.

Returns:

The ASN lookup results

{
    'asn' (str) - The Autonomous System Number
    'asn_date' (str) - The ASN Allocation date
    'asn_registry' (str) - The assigned ASN registry
    'asn_cidr' (str) - The assigned ASN CIDR
    'asn_country_code' (str) - The assigned ASN country code
    'asn_description' (None) - Cannot retrieve with this
        method.
}

Return type:

dict

Raises:
parse_fields_http(response, extra_org_map=None)[source]

The function for parsing ASN fields from a http response.

Parameters:
  • response (str) – The response from the ASN http server.
  • extra_org_map (dict) – 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’. Defaults to None.
Returns:

The ASN lookup results

{
    'asn' (None) - Cannot retrieve with this method.
    'asn_date' (None) - Cannot retrieve with this method.
    'asn_registry' (str) - The assigned ASN registry
    'asn_cidr' (None) - Cannot retrieve with this method.
    'asn_country_code' (None) - Cannot retrieve with this
        method.
    'asn_description' (None) - Cannot retrieve with this
        method.
}

Return type:

dict

Raises:
parse_fields_verbose_dns(response)[source]

The function for parsing ASN fields from a verbose dns response.

Parameters:

response (str) – The response from the ASN dns server.

Returns:

The ASN lookup results

{
    'asn' (str) - The Autonomous System Number
    'asn_date' (str) - The ASN Allocation date
    'asn_registry' (str) - The assigned ASN registry
    'asn_cidr' (None) - Cannot retrieve with this method.
    'asn_country_code' (str) - The assigned ASN country code
    'asn_description' (str) - The ASN description
}

Return type:

dict

Raises:
parse_fields_whois(response)[source]

The function for parsing ASN fields from a whois response.

Parameters:

response (str) – The response from the ASN whois server.

Returns:

The ASN lookup results

{
    'asn' (str) - The Autonomous System Number
    'asn_date' (str) - The ASN Allocation date
    'asn_registry' (str) - The assigned ASN registry
    'asn_cidr' (str) - The assigned ASN CIDR
    'asn_country_code' (str) - The assigned ASN country code
    'asn_description' (str) - The ASN description
}

Return type:

dict

Raises:
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 (str) – The starting IP address.
  • end_address (str) – The ending IP address.
Returns:

The calculated CIDR ranges.

Return type:

list of str

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 (bool) – Whether to use the older country code list (iso_3166-1_list_en.xml).
Returns:
A mapping of country codes as the keys to the country names as
the values.
Return type:dict
ipwhois.utils.ipv4_generate_random(total=100)[source]

The generator to produce random, unique IPv4 addresses that are not defined (can be looked up using ipwhois).

Parameters:total (int) – The total number of IPv4 addresses to generate.
Yields:str – The next IPv4 address.
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 (str) – An IPv4 address.
Returns:
is_defined (bool):
 True if given address is defined, otherwise False
ietf_name (str):
 IETF assignment name if given address is defined, otherwise ‘’
ietf_rfc (str):IETF assignment RFC if given address is defined, otherwise ‘’
Return type:namedtuple
ipwhois.utils.ipv4_lstrip_zeros(address)[source]

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

Parameters:address (str) – An IPv4 address.
Returns:The modified IPv4 address.
Return type:str
ipwhois.utils.ipv6_generate_random(total=100)[source]

The generator to produce random, unique IPv6 addresses that are not defined (can be looked up using ipwhois).

Parameters:total (int) – The total number of IPv6 addresses to generate.
Yields:str – The next IPv6 address.
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 (str) – An IPv6 address.
Returns:
is_defined (bool):
 True if given address is defined, otherwise False
ietf_name (str):
 IETF assignment name if given address is defined, otherwise ‘’
ietf_rfc (str):IETF assignment RFC if given address is defined, otherwise ‘’
Return type:namedtuple
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 (str) – The data to process.
  • file_path (str) – An optional file path to process.
Returns:

The addresses/networks mapped to ports and counts:

{
    '1.2.3.4' (dict) - Each address or network found is a
        dictionary:
        {
            'count' (int) - Total number of times seen.
            'ports' (dict) - Mapping of port numbers as keys and
                the number of times seen for this ip as values.
        }
}

Return type:

dict

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 (iter) – An iterable to process.
  • key (callable) – Optional function to run when checking elements (e.g., str.lower)
Yields:

The next unique element found.

exception ipwhois.exceptions.ASNLookupError[source]

An Exception for when the ASN lookup failed.

exception ipwhois.exceptions.ASNOriginLookupError[source]

An Exception for when the ASN origin lookup failed.

exception ipwhois.exceptions.ASNParseError[source]

An Exception for when the ASN parsing 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.BaseIpwhoisException[source]

Base exception for all the ipwhois custom ones.

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.

exception ipwhois.exceptions.WhoisRateLimitError[source]

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

ipwhois.experimental.bulk_lookup_rdap(addresses=None, inc_raw=False, retry_count=3, depth=0, excluded_entities=None, rate_limit_timeout=60, socket_timeout=10, asn_timeout=240, proxy_openers=None)[source]

The function for bulk retrieving and parsing whois information for a list of IP addresses via HTTP (RDAP). This bulk lookup method uses bulk ASN Whois lookups first to retrieve the ASN for each IP. It then optimizes RDAP queries to achieve the fastest overall time, accounting for rate-limiting RIRs.

Parameters:
  • addresses (list of str) – IP addresses to lookup.
  • inc_raw (bool, optional) – Whether to include the raw whois results in the returned dictionary. Defaults to False.
  • retry_count (int) – The number of times to retry in case socket errors, timeouts, connection resets, etc. are encountered. Defaults to 3.
  • depth (int) – How many levels deep to run queries when additional referenced objects are found. Defaults to 0.
  • excluded_entities (list of str) – Entity handles to not perform lookups. Defaults to None.
  • rate_limit_timeout (int) – The number of seconds to wait before retrying when a rate limit notice is returned via rdap+json. Defaults to 60.
  • socket_timeout (int) – The default timeout for socket connections in seconds. Defaults to 10.
  • asn_timeout (int) – The default timeout for bulk ASN lookups in seconds. Defaults to 240.
  • proxy_openers (list of OpenerDirector) – Proxy openers for single/rotating proxy support. Defaults to None.
Returns:

results (dict):IP address keys with the values as dictionaries returned by IPWhois.lookup_rdap().
stats (dict):Stats for the lookups:
{
    'ip_input_total' (int) - The total number of addresses
        originally provided for lookup via the addresses argument.
    'ip_unique_total' (int) - The total number of unique addresses
        found in the addresses argument.
    'ip_lookup_total' (int) - The total number of addresses that
        lookups were attempted for, excluding any that failed ASN
        registry checks.
    'lacnic' (dict) -
    {
        'failed' (list) - The addresses that failed to lookup.
            Excludes any that failed initially, but succeeded after
            futher retries.
        'rate_limited' (list) - The addresses that encountered
            rate-limiting. Unless an address is also in 'failed',
            it eventually succeeded.
        'total' (int) - The total number of addresses belonging to
            this RIR that lookups were attempted for.
    }
    'ripencc' (dict) - Same as 'lacnic' above.
    'apnic' (dict) - Same as 'lacnic' above.
    'afrinic' (dict) - Same as 'lacnic' above.
    'arin' (dict) - Same as 'lacnic' above.
    'unallocated_addresses' (list) - The addresses that are
        unallocated/failed ASN lookups. These can be addresses that
        are not listed for one of the 5 RIRs (other). No attempt
        was made to perform an RDAP lookup for these.
}

Return type:

namedtuple

Raises:

ASNLookupError – The ASN bulk lookup failed, cannot proceed with bulk RDAP lookup.

ipwhois.experimental.get_bulk_asn_whois(addresses=None, retry_count=3, timeout=120)[source]

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

Parameters:
  • addresses (list of str) – IP addresses to lookup.
  • retry_count (int) – The number of times to retry in case socket errors, timeouts, connection resets, etc. are encountered. Defaults to 3.
  • timeout (int) – The default timeout for socket connections in seconds. Defaults to 120.
Returns:

The raw ASN bulk data, new line separated.

Return type:

str

Raises:
  • ValueError – addresses argument must be a list of IPv4/v6 address strings.
  • ASNLookupError – The ASN bulk lookup failed.