Skip to content
internetdataPublic

About

Official Go client library for the InternetData API: look up any IP address, AS or domain, and download the databases.

Topics

Resources

Security policy

Stars

1 star

Watchers

1 watching

Forks

Latest commit

 

History

155 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

InternetData InternetData Go Client Library

Go Reference license

The official Go client library for the InternetData API.

It tells you what InternetData's databases say about an IP address, an AS or a domain, and downloads the databases your organization is licensed for, in CSV.GZ or MMDB.

Getting Started

go get github.com/internetdata/sdk-go/v3

Requires Go 1.26 or newer. The module path ends in sdk-go, but the package it declares is internetdata:

import internetdata "github.com/internetdata/sdk-go/v3"

Usage

No API key needed to try it. A lookup without a key answers the basics: where an address is, the AS behind it, whether it's a Tor exit, a relay or anycast, and its hostname. The address's company and its abuse contact are a free key's full answers' or a paid plan's, and a free key answers every field on its organization's first lookups each UTC day, then raises quota_exceeded (below).

client, err := internetdata.New()
if err != nil {
    log.Fatal(err)
}

result, err := client.Lookup(ctx, "146.70.116.130")
if err != nil {
    log.Fatal(err)
}
fmt.Println(result.Location.Country)   // AT
fmt.Println(result.Asn.Name)           // M247 Europe SRL
fmt.Println(result.IsTor)              // false

With an API key

A paid plan answers every field: is_vpn, is_hosting, is_cdn and the four proxy flags as well, the provider and confidence behind each flag, whose bot uses the address, the location down to the city, and the whois record. A free key answers every field on its organization's first lookups each UTC day, then raises quota_exceeded. Create a key in the console, then pass it in:

client, err := internetdata.New(internetdata.WithAPIKey(os.Getenv("INTERNETDATA_API_KEY")))

result, err := client.Lookup(ctx, "146.70.116.130")
fmt.Println(internetdata.BoolValue(result.IsVpn))   // true, on a paid plan

if vpn := result.Vpn; vpn != nil {
    fmt.Println(vpn.ProviderName)       // Mullvad, on a paid plan
}
if bot := result.Bot; bot != nil && internetdata.BoolValue(result.IsBot) {
    fmt.Println(*bot.Agents)            // [Googlebot] for a crawler's address, on a paid plan
}

When your lookups are used up

Once your organization's lookups with every field are used up (a free key's for the UTC day, a paid key's quota or overage cap), the API keeps answering your key with the basics and cap_reached: true. The library never hands that back as a full answer, which would let your program run on without the fields it was built on: the call returns a *internetdata.CappedError instead, quota_exceeded with status 200, never retried, whose message is this organization's lookups with every field are used up; this answer has the basics. Catching it is the one way to carry on, and no option turns it off. Result holds the basics:

result, err := client.Lookup(ctx, "146.70.116.130")
var capped *internetdata.CappedError[internetdata.Result]
if errors.As(err, &capped) {
    // quota_exceeded: this answer has the basics.
    fmt.Println(capped.Result.Location.Country)   // AT
} else if err != nil {
    log.Fatal(err)
}

The error unwraps to an *internetdata.Error, so errors.As into one finds Kind == KindQuotaExceeded too. Lookup, MyIP and a batch's entries carry a CappedError[Result], LookupASN a CappedError[AsnLookupResponse] and LookupDomain a CappedError[DomainLookupResponse]. A private or reserved address and a lookup without a key never raise it. A capped answer is cached for a minute at most, and each lookup it answers raises again: a busy address costs one request a minute.

An AS or a domain

asn, err := client.LookupASN(ctx, 9009)
fmt.Println(asn.Name, asn.Country)     // M247 Europe SRL RO

domain, err := client.LookupDomain(ctx, "example.com")
fmt.Println(domain.IsRegistered)       // true

Every plan answers an AS's registration and whether a domain is registered and which record types it has. A paid plan adds the AS's whois record, its prefixes, its rank, Tier 1 flag, upstreams, peers and downstreams, and the domains it hosts, and the domain's records, the network announcing each of its addresses, the other domains on its first IPv4 address, its IP ranges, is_disposable, what its home page says and links to, and the domains whose home page redirects or links to it. Neither is cached or batched, and Lookup takes an address alone: it refuses anything else as a bad_request before sending it.

Your own address

result, err := client.MyIP(ctx)
fmt.Println(result.IP)   // the address we saw this call come from

Same answer Lookup would give for that address, and the same cost against your allowance. It's deliberately not cached: which address you are is the whole question, and a machine that moves between networks would otherwise be told where it used to be.

Your plan and usage

acct, err := client.MyEntitlement(ctx)
fmt.Println(acct.Plan.Key)         // data_4
fmt.Println(acct.Plan.Name)        // Data, the name to show
fmt.Println(acct.Usage.Requests)   // 580
fmt.Println(acct.Usage.WindowEnd)  // when the allowance resets

Usage is counted against the anniversary of your subscription on a paid plan, not the calendar month and not the billing period; it's the same number a lookup is gated on. HardLimit is nil on an uncapped plan, which is not the same as zero.

Batch lookup

Look up many addresses at once. Bogons and cached answers are handled locally, and everything else goes to the batch endpoint in chunks of up to 1000 addresses, in parallel. The batch endpoint needs a paid plan:

results, err := client.LookupBatch(ctx, []string{"146.70.116.130", "8.8.8.8", "1.1.1.1"})

for ip, result := range results {
    if result.Err != nil {
        fmt.Printf("%s: %v\n", ip, result.Err)
        continue
    }
    fmt.Printf("%s: %s\n", ip, result.Result.Location.Country)
}

Results are keyed by address, so duplicates in your list collapse into a single entry and one address failing never loses the rest: it carries its error as its value, with the status the API would have given that address on its own. An address answered with the basics because your lookups are used up carries a *internetdata.CappedError[internetdata.Result] as its Err, holding that answer, and the batch still returns.

Pass as many addresses as you like; splitting them into chunks is the library's job. How many chunks are in flight at once, how many times a failed chunk is retried, and how long each attempt may take are configurable per call:

results, err := client.LookupBatch(ctx, manyIPs,
    internetdata.Concurrency(4), internetdata.Retries(4), internetdata.Timeout(10*time.Second))

Retries and Timeout work on Lookup, LookupASN, LookupDomain, MyIP and MyEntitlement too. The timeout bounds each attempt rather than the whole call, and defaults to the HTTP client's: 30 seconds unless WithHTTPClient supplied another.

Every request names the SDK in its User-Agent, internetdata-go/<version>, object storage's included. A program built on the SDK can put its own name first in the transport it passes to WithHTTPClient, which sees that header already set.

A visitor's user agent

Pass the User-Agent of the request you are deciding on, and with every field (a paid plan or a free key's full answers) the answer says whose bot it names and whether this address bears that out, so a real crawler can be told from one forging its agent:

result, err := client.Lookup(ctx, ip, internetdata.UserAgent(r.UserAgent()))
if result.UserAgent != nil && result.UserAgent.Verdict == internetdata.VerdictVerified {
    // Googlebot, from one of Google's own addresses.
}

results, err := client.LookupBatch(ctx, ips, internetdata.UserAgents(map[string]string{
    "66.249.66.1": "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
}))

The verdict is VerdictVerified, VerdictSpoofed, VerdictUnverifiable or VerdictNotBot. UserAgent works on MyIP too, and on a batch it is every address's agent except one UserAgents names. An empty agent sends none, and UserAgent is nil in the basics, a lookup without a key's and a free key's past its full answers for the day, and for a private or reserved address. An answer for an address and an agent is cached apart from that address's plain answer.

Caching

Address lookups are cached by default, so repeat lookups of the same address are free:

client, err := internetdata.New()

result, err := client.Lookup(ctx, "146.70.116.130")
fmt.Println(result.Asn.Asn)    // 9009, API request

result2, err := client.Lookup(ctx, "146.70.116.130")
fmt.Println(result2.Asn.Asn)   // 9009, no API request, result was cached

You can change the default cache variables (max size, TTL, etc) on initialization, or even disable it:

client, err := internetdata.New(internetdata.WithCache(50_000, 6*time.Hour))
clientNoCache, err := internetdata.New(internetdata.WithoutCache())

Private and reserved addresses

Private, loopback, link-local, documentation and multicast addresses (and their IPv6 equivalents, including the 6to4 and Teredo ranges) are answered locally, every flag false and every field empty, so they cost no request and no quota:

result, err := client.Lookup(ctx, "192.168.1.1")
result.IsBogon   // true, this answer was computed rather than served
result.IsTor     // false

Because the answer is computed rather than served, it always carries every field, whatever plan you are on. Do not read your plan's shape off a private address.

The check is available on the client, which is handy when your inputs are addresses anyway:

client.IsBogon("10.0.0.1")   // true
client.IsBogon("8.8.8.8")    // false

It is also callable on its own, if you want it without a client:

internetdata.IsBogon("10.0.0.1")   // true

Errors

Failures return an *internetdata.Error carrying a Kind, the API's own message, and a Retryable flag:

result, err := client.Lookup(ctx, "146.70.116.130")
var apiErr *internetdata.Error
if errors.As(err, &apiErr) {
    fmt.Println(apiErr.Kind, apiErr.Message, apiErr.Retryable())
}

Kind is one of bad_request, unauthorized, forbidden, rate_limited, quota_exceeded, server_error or network. A lookup's Message is the API's explanation. A database call's is its rc, which is what separates two refusals that share a status: NOT_LICENSED means buy it, LICENSE_EXPIRED means renew it, and IP_NOT_ALLOWED means the call came from an address the key or its organization does not allow, and all three are 403.

Note that rate_limited and quota_exceeded both arrive as HTTP 429 and are not the same thing. A rate limit carries Retry-After, and retrying later works; one without it is quota_exceeded. The library retries rate limits for you, but never quota_exceeded. A lookup without a key from an address that has used the day's allowance is answered a 429 without Retry-After: its Message says where to get a free key, and a key, or the next UTC day, is the way out. An answer with cap_reached: true raises quota_exceeded too, with status 200 and the answer in a *internetdata.CappedError: above.

Databases

The databases your organization is licensed for are under client.Database, for a key carrying the db.download scope. Every database published today is licensed:

client, err := internetdata.New(internetdata.WithAPIKey(os.Getenv("INTERNETDATA_API_KEY")))

databases, err := client.Database.List(ctx)
for _, db := range databases {
    fmt.Println(db.Base, db.Standing)   // bogon_ip licensed
}

Every database call hangs off client.Database, which is where the sibling VPNDetection library keeps the same seven calls.

The catalog

List returns one entry per database FAMILY, with your license beside it. A license covers the family, while a download names one of its versions, so the IDs you pass to everything else come from Versions:

for _, db := range databases {
    if db.Standing != internetdata.StandingLicensed {
        continue
    }
    for _, v := range db.Versions {
        fmt.Println(v.ID, v.Formats)    // vpn_ip_v1 [csvgz mmdb]
    }
}

Standing is licensed, expired or unlicensed, and LicenseType is what your license permits: evaluation, standard, redistribute, or nil when there is no license at all. Old versions are frozen rather than migrated, so both stay downloadable.

What is inside one, before you fetch it

Metadata carries the row count, the build date, the columns of each format and the byte size of each file, without downloading anything. Poll it to decide whether today's build is worth fetching, and read Size to budget a transfer before you start one:

meta, err := client.Database.Metadata(ctx, "vpn_ip_v1")
fmt.Println(meta.Updated, meta.Entries, meta.Size["mmdb"])

for _, column := range meta.Schema["csvgz"] {
    fmt.Println(column.Name, column.Type)
}

Downloading

DownloadFile writes one file to a path, streaming it straight to disk so that nothing bigger than a chunk is ever held in memory:

written, err := client.Database.DownloadFile(ctx, "vpn_ip_v1", internetdata.FormatMMDB, "./vpn_ip_v1.mmdb")
fmt.Printf("%d bytes\n", written)

The bytes land in a neighboring .part file that is renamed on completion, so a transfer that dies half way leaves no truncated file that reads as a whole database, and a failed refresh cannot destroy the copy already there.

Or stream it into a writer of your own, or take a small one as bytes:

written, err := client.Database.Download(ctx, "vpn_ip_v1", internetdata.FormatMMDB, w)
raw, err := client.Database.DownloadBytes(ctx, "bogon_ip_v1", internetdata.FormatCSVGZ)

DownloadBytes holds the whole file in memory, and the catalog spans five orders of magnitude, so use DownloadFile for anything you have not measured against Metadata's Size.

Format is a defined string type, so Format("zip") compiles. Anything the API does not publish is refused before the request leaves, as a bad_request naming what is allowed; Valid is the same check for a format you take from a flag or a config file:

if !internetdata.Format(fromFlag).Valid() {
    // csvgz or mmdb
}

Downloading a named build

Each download call fetches the build that is live unless you name one. A database.updated webhook names the build it announces and carries its sha256, so a receiver that downloads after the next publish asks for that build to get the file the hash is of. client.Database.AtBuild(build) has the same four download calls, for that build:

written, err := client.Database.AtBuild(event.Data.Build).DownloadFile(ctx,
    "vpn_ip_v1", internetdata.FormatMMDB, "./vpn_ip_v1.mmdb")

A build is kept 7 days. Past that the call fails as bad_request with the message BUILD_GONE, and client.Database's own download calls fetch the live one.

Downloading it yourself

The API answers a download with a redirect to a time-limited URL on object storage. DownloadURL hands you that URL rather than following it, so you can pass it to a downloader, a job queue or another machine:

url, err := client.Database.DownloadURL(ctx, "vpn_ip_v1", internetdata.FormatMMDB)

The link is presigned and so authorizes itself; it carries no API key of yours, and the library never sends your key to object storage. The link only has to be valid when a transfer starts, so one already running isn't cut off when it lapses.

Verifying a download

Checksums returns all four digests the exporter publishes for one file:

sums, err := client.Database.Checksums(ctx, "vpn_ip_v1", internetdata.FormatMMDB)
fmt.Println(sums.SHA256)

Download history

Downloads is your organization's recent attempts, newest first, refusals included: a denial is what answers "it stopped working", and its absence answers nothing.

history, err := client.Database.Downloads(ctx, 50)
for _, attempt := range history {
    fmt.Println(attempt.Created, attempt.DatasetID, attempt.Outcome)
}

Sign in with OAuth (device flow)

A program running on the person's own machine can let them sign in with a browser and pick one of their API keys, instead of asking them to paste it:

client, err := internetdata.New()
device, err := client.Oauth.DeviceAuthorization(ctx, "your-client-id",
    internetdata.DeviceAuthorizationOptions{Scope: "account.read apikeys.read apikeys.reveal"})
fmt.Printf("Open %s and enter %s\n", device.VerificationURI, device.UserCode)

token, err := client.Oauth.PollDeviceToken(ctx, "your-client-id", device)
if token.Apikey == nil {
    log.Fatal("no API key came back: none was picked, or it cannot be revealed")
}
keyed, err := internetdata.New(internetdata.WithAPIKey(*token.Apikey))

A denied sign-in satisfies errors.Is(err, internetdata.ErrOauthAccessDenied) and a code that ran out errors.Is(err, internetdata.ErrOauthExpiredToken). client.Oauth.Revoke(ctx, "your-client-id", *token.RefreshToken) signs the machine out again. Only a client we registered, such as our CLI, can use the device flow: an app of your own signs people in with the authorization code flow below.

Sign in with OAuth (authorization code)

An app that can take a browser redirect signs the person in there instead, with a PKCE pair made for that one sign-in:

client, err := internetdata.New()
redirectURI := "http://127.0.0.1:8765/callback"
pkce := client.Oauth.CreatePkce()

authURL, err := client.Oauth.AuthorizationURL("your-client-id", redirectURI, pkce.Challenge,
    internetdata.AuthorizationURLOptions{Scope: "apikeys.use", State: "your-state"})
// Open authURL in the browser. Its redirect to redirectURI carries code and state.
token, err := client.Oauth.ExchangeAuthorizationCode(ctx, "your-client-id", code, pkce.Verifier, redirectURI)

Check that state came back as you sent it before you exchange code, which works once. The client ID can also be the https URL of a client metadata document your app serves, and such an app is never handed a key, so token.Apikey stays nil.

Register a client

An app with no client ID, and no client metadata document to use as one, registers itself, then signs in with the ClientID it gets back as the client ID for AuthorizationURL and ExchangeAuthorizationCode:

client, err := internetdata.New()
registration, err := client.Oauth.Register(ctx, []string{"http://127.0.0.1:8765/callback"},
    internetdata.RegisterOptions{ClientName: "Your App"})

Each redirect URI must be https on a public host name, or http on a loopback address, which then matches any port. Nothing is kept until a person approves the client, so an app with no client ID saved can simply register again.

Absent is not false

Beyond the members every answer carries, each field is a pointer, because your key decides which of them the API sends, and so is each paid field inside a shared object, such as Location.City or Abuse.Phone. The basics, which a lookup without a key gets, and the basics a capped answer carries in its CappedError, leave out IsVpn, IsHosting, IsCdn, the four proxy flags, the eight service flags (IsBot, IsCarrier, IsSatellite, IsSSH, IsSMTP, IsWeb, IsDNSResolver and IsBittorrent), the AS's type, the company, the abuse contact, the detail behind each flag but Tor's and relay's, and the whois record. A nil pointer means "not in this answer", not "checked, and no": each of those reads nil when the answer leaves it out, never false, "" or an empty struct. An answer to a key carries CapReached, false while it has every field.

internetdata.BoolValue(result.IsVpn)        // when you only want the flag
result.IsVpn == nil                         // in the basics: not in this answer
result.Company == nil                       // the company is a full answer's
internetdata.BoolValue(result.CapReached)   // false on any answer a lookup returns

Other Libraries

There are official InternetData client libraries available for many languages including PHP, Python, Go, Java, and Ruby. See our GitHub at https://github.com/internetdata for more.

About InternetData

Geolocation, anonymity, ownership, network, service and domain data for any IP address, AS or domain, by API or as databases you download.

InternetData

License

This project is licensed under the MIT License.

About

Official Go client library for the InternetData API: look up any IP address, AS or domain, and download the databases.

Topics

Resources

Security policy

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages