Skip to main content

Crate ipregistry

Crate ipregistry 

Source
Expand description

Official Rust client for the Ipregistry IP geolocation and threat data API.

Look up your own IP address or specified ones. Responses return multiple data points including carrier, company, currency, location, time zone, threat information, and more. The library can also parse raw User-Agent strings.

You’ll need an Ipregistry API key, which you can get along with 100,000 free lookups by signing up for a free account at https://ipregistry.co.

§Quick start

use std::net::IpAddr;
use ipregistry::Client;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new("YOUR_API_KEY");

    // Look up data for a given IPv4 or IPv6 address. On the server side,
    // parse the client IP from the request headers.
    let ip: IpAddr = "54.85.132.205".parse()?;
    let info = client.lookup(ip).await?;
    println!("{}", info.location.country.name);

    // Look up the IP address the request originates from.
    let origin = client.lookup_origin().await?;
    println!("{:?} {}", origin.info.ip, origin.info.location.country.name);

    Ok(())
}

Lookups are refined by chaining methods on the request before awaiting it:

let info = client
    .lookup(ip)
    .hostname(true)                            // resolve reverse-DNS hostname
    .fields("location.country.name,security")  // select only these fields
    .await?;

§Batch lookups

Client::lookup_batch resolves many IP addresses in a single request. Each entry independently succeeds or fails (for example on a reserved address), so entries are plain Result values:

use std::net::IpAddr;

let ips: Vec<IpAddr> = ["73.2.2.2", "8.8.8.8", "2001:67c:2e8:22::c100:68b"]
    .iter()
    .map(|s| s.parse().unwrap())
    .collect();

for entry in client.lookup_batch(ips).await? {
    match entry {
        Ok(info) => println!("{}", info.location.country.name),
        Err(err) => eprintln!("entry failed: {err}"),
    }
}

The Ipregistry API accepts up to MAX_BATCH_SIZE IP addresses per request; larger inputs are transparently split into several requests dispatched with bounded concurrency and reassembled in input order.

§Caching

Caching is disabled by default to ensure data freshness. Enable it by passing an InMemoryCache — thread-safe, with LRU and TTL eviction — or any Cache implementation of your own:

use std::time::Duration;
use ipregistry::{Client, InMemoryCache};

let cache = InMemoryCache::builder()
    .max_size(8192)
    .ttl(Duration::from_secs(600))
    .build();

let client = Client::builder("YOUR_API_KEY").cache(cache).build().unwrap();

§Errors

All operations return Error, which separates failures reported by the API (Error::Api, carrying a typed ErrorCode) from client-side failures such as network errors (Error::Transport). See the Error documentation for a matching example.

§Runtime

The client is asynchronous and runs on the Tokio runtime. A Client is cheap to clone and safe to share across tasks; spawn concurrent lookups freely.

Re-exports§

pub use model::IpInfo;
pub use model::RequesterIpInfo;
pub use model::UserAgent;
pub use model::is_bot;
pub use reqwest;

Modules§

model
Data types returned by the Ipregistry API.

Structs§

ApiError
A failure reported by the Ipregistry API, such as an invalid IP address, an exhausted credit balance, or throttling.
Client
A client for the Ipregistry API. Create one with Client::new or Client::builder.
ClientBuilder
Builds a Client. Create one with Client::builder.
InMemoryCache
A thread-safe, in-process Cache with time-based expiration and a bounded size using least-recently-used eviction.
InMemoryCacheBuilder
Builds an InMemoryCache. Create one with InMemoryCache::builder.
LookupBatchRequest
A batch IP lookup request. Created with Client::lookup_batch; await it (or call send) to execute it.
LookupOriginRequest
An origin (requester) IP lookup request. Created with Client::lookup_origin; await it (or call send) to execute it.
LookupRequest
A single-IP lookup request. Created with Client::lookup; await it (or call send) to execute it.

Enums§

Error
The error type returned by all client operations.
ErrorCode
A strongly typed Ipregistry API error code. It lets callers branch on error conditions without matching on raw strings. See https://ipregistry.co/docs/errors for the authoritative list.

Constants§

DEFAULT_BASE_URL
The base URL of the Ipregistry API used unless overridden with ClientBuilder::base_url.
DEFAULT_BATCH_CONCURRENCY
The default number of batch sub-requests dispatched concurrently when a batch lookup is split into chunks.
DEFAULT_CACHE_MAX_SIZE
Default maximum number of entries held by an InMemoryCache.
DEFAULT_CACHE_TTL
Default time-to-live of InMemoryCache entries.
DEFAULT_MAX_RETRIES
The default maximum number of automatic retries performed in addition to the initial attempt.
DEFAULT_RETRY_INTERVAL
The default base backoff between retries.
DEFAULT_TIMEOUT
The default per-request timeout.
MAX_BATCH_SIZE
The maximum number of IP addresses Ipregistry accepts in a single batch request. Client::lookup_batch transparently splits larger inputs into several requests so callers never have to.

Traits§

Cache
Abstracts the storage used by a Client to memoize IP lookups. Implementations must be safe for concurrent use from multiple threads and should never block for long, as they are called from async contexts.

Type Aliases§

Result
A convenient alias for results produced by this crate.