The official Swift client library for the InternetData API.
It tells you what every InternetData database says about an IP address, an AS or a domain, and it downloads the databases your organization is licensed for.
Add the package to your Package.swift:
dependencies: [
.package(url: "https://github.com/internetdata/sdk-swift.git", from: "4.0.0"),
]and the library to your target. The repository ends in sdk-swift, which is the package name SwiftPM derives, but the library it exposes is InternetData:
.target(
name: "YourTarget",
dependencies: [.product(name: "InternetData", package: "sdk-swift")],
)Requires Swift 6.1 or newer, and macOS 13, iOS 16, tvOS 16, watchOS 9 or visionOS 1 on Apple platforms. Linux is supported on any distribution the Swift toolchain runs on.
No API key needed to try it. A lookup without one answers the basics: the address's country, its AS, its reverse DNS name, and the Tor, relay and anycast flags. The address's company and its abuse contact are not in the basics: they are a free key's full answers' or a paid plan's. A free key answers more (below).
import InternetData
let client = InternetDataClient()
let result = try await client.lookup("146.70.116.130")
print(result.location.country) // AT
print(result.asn.name) // M247 Europe SRL
print(result.isTor) // falseA paid plan answers every field: who uses the address and its abuse contact, the VPN, proxy, hosting and CDN flags and the provider and confidence behind each, the bot, carrier, satellite, SSH, SMTP, web, DNS resolver and BitTorrent flags and the rows behind them, including whose bot uses the address and whether its operator vouches for it, whether a request's user agent is borne out by its address (below), the city and the coordinates, the Whois records, and the hosted domains, a count and the 10 most popular. Its quotas differ only in how many lookups they include. A free key answers every field on its organization's first lookups each UTC day, then the basics. Create a key in the console, then pass it in:
let client = InternetDataClient(apiKey: ProcessInfo.processInfo.environment["INTERNETDATA_API_KEY"]!)
let result = try await client.lookup("146.70.116.130")
print(result.isVpn) // Optional(true), on a paid plan
print(result.vpn?.providerName) // Optional("Mullvad"), on a paid plan
print(result.location.city) // Optional("Vienna"), on a paid planEvery setting has a default, and InternetDataClient.Options is where you change one:
let client = InternetDataClient(options: .init(apiKey: key, concurrency: 32, retries: 4))Your organization's key has an allowance of lookups with every field: a free key's is the UTC day's, and a paid key's is its quota, or its overage cap where overage is on. Past it the API keeps answering, with the basics and capReached true, and a call that reads such an answer throws quotaExceeded rather than hand it back, so a program never runs on without the fields it was built on without anyone noticing. The error has status 200, is never retried, and carries the answer in result, typed as the call's: .lookup for lookup, myIP and a batch entry, .asn for lookupASN and .domain for lookupDomain. No option turns it off, and catching it is how you carry on:
do {
let result = try await client.lookup("146.70.116.130")
print(result.isVpn ?? false)
} catch let error as InternetDataError where error.kind == .quotaExceeded {
// This organization's lookups with every field are used up; the answer has the basics.
if case .lookup(let basics)? = error.result {
print(basics.location.country) // AT
}
}A bogon and a call without a key never throw it: neither carries capReached. A quotaExceeded that is a 429 has no result.
let result = try await client.myIP()
print(result.ip) // the address we saw this call come fromSame answer lookup would give for that address, and the same cost against your allowance. It is 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.
Pass the User-Agent header of the request you are deciding on, and with every field the answer carries userAgent: the agent it names, what kind of client that is, and whether this address bears it out. A request claiming to be Googlebot from an address Google does not vouch for comes back spoofed:
let result = try await client.lookup(visitorIP, userAgent: userAgentHeader)
if let ua = result.userAgent {
print(ua.agent) // Googlebot
print(ua.kind) // bot
print(ua.verdict == .verified) // true: Google vouches for this address
}verdict is .verified, .spoofed, .unverifiable (a bot nothing published can confirm) or .notBot (a browser, an app or a script), and reads a value the API adds later as itself (below). myIP(userAgent:) takes one too, and a batch takes each address's, keyed by the address as you list it:
let results = try await client.lookupBatch(ips, userAgents: ["66.249.66.1": googlebotHeader])An answer is cached per address and user agent, so the same address with another agent, or with none, is a request of its own. An empty user agent is none, and one longer than 1024 characters is sent and cut there by the API. A private or reserved address is answered locally and carries no userAgent. An answer with only the basics never carries it.
let asn = try await client.lookupASN(9009)
print(asn.name, asn.registry) // M247 Europe SRL ripe
let domain = try await client.lookupDomain("example.com")
print(domain.isRegistered) // true
print(domain.dns?.mx.first?.host) // on a paid planA paid plan adds an AS's Whois record, the prefixes it announces, its rank, Tier 1 flag, upstreams, peers and downstreams, and the domains it hosts, and a domain's DNS records, the network announcing each of its addresses, the other domains on its first IPv4 address, its organization's IP ranges, whether it's a disposable email domain, 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 an AS or a domain as badRequest before sending anything.
let acct = try await client.myEntitlement()
print(acct.plan.key) // data_4
print(acct.plan.name) // Data, the name to show
print(acct.usage.requests) // 580
print(acct.usage.windowEnd) // when the allowance resetsUsage counts against the anniversary of your subscription on a paid plan, not the calendar month and not the billing period, and against the UTC day on the free plan; it is the same number a lookup is gated on. hardLimit is nil on an uncapped plan, which is not the same as zero.
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:
let results = try await client.lookupBatch(["146.70.116.130", "8.8.8.8", "1.1.1.1"])
for (ip, outcome) in results {
switch outcome {
case .success(let result):
print("\(ip): \(result.asn.name)")
case .failure(let error):
print("\(ip): \(error)")
}
}Results are keyed by address, in the order you first listed each one, 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 only the basics (capReached true) fails the same way: its value is the quotaExceeded error, with the answer in error.result, and results.values leaves it out. results["8.8.8.8"] gets one back on its own, and results.keys is the order you passed in.
How many chunks are in flight at once, how many times a failed chunk is retried, and how long each attempt at a chunk may take, are configurable per call:
let results = try await client.lookupBatch(manyIps, options: .init(concurrency: 4, retries: 4, timeout: .seconds(10)))Answers are cached by default, so repeat lookups of the same address are free:
let client = InternetDataClient()
let result = try await client.lookup("146.70.116.130")
print(result.asn.name) // M247 Europe SRL, API request
let result2 = try await client.lookup("146.70.116.130")
print(result2.asn.name) // M247 Europe SRL, no API request, result was cachedYou can change the default cache variables (max size, TTL, etc) on initialization, or even disable it:
let client = InternetDataClient(options: .init(cache: .init(maxEntries: 50_000, ttl: .seconds(6 * 3600))))
let clientNoCache = InternetDataClient(options: .init(cache: nil))An answer with capReached true is cached for a minute at most, so the next day's full answers or a raised cap reach you within a minute, and each hit throws quotaExceeded again: a busy address costs one request a minute, never one per call.
Private, loopback, link-local, documentation and multicast addresses (and their IPv6 equivalents, including the 6to4 and Teredo ranges) are reserved space no database says anything about. The library answers them locally, so they cost no request and no quota:
let result = try await client.lookup("192.168.1.1")
result.isBogon // true
result.isVpn // Optional(false)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") // falseIt is also a free function, if you want it without a client:
import InternetData
isBogon("10.0.0.1") // trueFailures throw an InternetDataError carrying a kind, the API's own message, and an isRetryable flag:
do {
_ = try await client.lookup("146.70.116.130")
} catch let error as InternetDataError {
print(error.kind, error.message, error.isRetryable)
}kind is one of badRequest, unauthorized, forbidden, rateLimited, quotaExceeded, serverError or network. A database call's message is the API's rc, such as NOT_LICENSED.
Note that rateLimited and quotaExceeded both arrive as HTTP 429 and are not the same thing. A rate limit carries Retry-After, so retrying later works; but one without it is quotaExceeded, such as when the day's lookups without a key from your address are used up and a free key answers more. The library retries rate limits for you, waiting as long as the API asks, but never quotaExceeded. A key past its organization's allowance is never answered with a 429: it gets the basics with capReached, and that answer throws quotaExceeded too, with the answer as error.result (above).
Each attempt is abandoned after 30 seconds by default (timeout on the options), which fails as a retryable network error. A download is timed only until object storage starts answering, so a large file is never cut off. One call can set its own, longer or shorter - lookup, myIP, lookupASN, lookupDomain, myEntitlement, a batch, every oauth method, and every client.database call but the transfers:
let result = try await client.lookup("146.70.116.130", timeout: .seconds(5))
let databases = try await client.database.list(timeout: .seconds(5))lookup, myIP, lookupASN, lookupDomain, myEntitlement and a batch take retries for that call alone the same way, and one below zero is refused as badRequest before any request.
Every database published today needs an API key carrying the db.download scope. The Open databases are licensed to every organization from the start and are free under CC BY-SA 4.0, and list() marks them open. The rest are licensed by contract, one family at a time: if your organization doesn't have a license yet, request an evaluation.
let client = InternetDataClient(apiKey: ProcessInfo.processInfo.environment["INTERNETDATA_API_KEY"]!)
for database in try await client.database.list() {
print(database.base, database.standing, database.versions.map(\.id))
// vpn_ip licensed ["vpn_ip_v1"]
}The database calls live under client.database, where the sibling VPNDetection client spells the same seven the same way, so a codebase holding both does not have to remember which one is flat.
A license is held against a FAMILY (vpn_ip), while a download names a VERSION (vpn_ip_v1), so the IDs everything below takes come from versions. Old versions are frozen rather than migrated, so both stay downloadable.
list, metadata, checksums, downloads and downloadURL each take a timeout of their own. The transfers deliberately take none, so there is nothing to pass and a call that tries does not compile rather than accepting the option and quietly doing nothing with it: a database runs to gigabytes and minutes, so any bound that suits a JSON call would abandon a healthy download. downloadURL does take one, because minting the link is an ordinary API request - it bounds that request, not whatever you do with the link afterwards.
metadata carries the build date, the row count, the columns and the size of every format, without downloading anything. Poll it to decide whether today's build is worth fetching, and read size to budget the transfer:
let metadata = try await client.database.metadata(id: "vpn_ip_v1")
print(metadata.updated) // "2026-09-04"
print(metadata.entries) // 3_214_887
print(metadata.size["mmdb"]) // Optional(48_213_504)
print(metadata.schema["csvgz"]?.map(\.name) ?? [])
print(metadata.sample["csvgz"]?.first ?? [:])Not every database is built in every format: the _provider catalogs are keyed by provider ID rather than by IP range, so asking them for an MMDB is a badRequest rather than a gap. DatabaseVersion.formats says which exist.
download streams straight to disk, so nothing bigger than a single chunk is ever held in memory whatever the file weighs. It writes a neighbouring .part file and renames it on success, so a transfer that dies half way leaves nothing that reads as a whole database:
let written = try await client.database.download(
"vpn_ip_v1", format: .mmdb,
to: URL(fileURLWithPath: "vpn_ip_v1.mmdb"),
)
print("\(written) bytes")Hand it a closure instead when the bytes are going somewhere other than a file: a parser, an archive, another socket. The closure is awaited, so a slow sink slows the transfer rather than queueing behind it:
try await client.database.download("vpn_ip_v1", format: .csvgz) { chunk in
try await gunzip.write(chunk)
}downloadBytes hands the whole file back at once. It holds all of it in memory, and the catalog spans seven orders of magnitude, so reach for it at the small end and use download for anything you have not measured:
let bytes = try await client.database.downloadBytes("bogon_asn_v1", format: .csvgz)The API answers a download with a 302 to a time-limited link that carries its own signature, so downloadURL gives you something you can pass to a job runner, a CDN or a shell script that holds no API key at all:
let url = try await client.database.downloadURL(id: "vpn_ip_v1", format: .mmdb)The link only has to be valid when a transfer starts, so one already running isn't cut off when it lapses.
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:
try await client.database.download("vpn_ip_v1", format: .mmdb, build: build, to: destination)downloadURL and downloadBytes take build: the same way. A build is kept 7 days. Past that the call throws badRequest with the message BUILD_GONE, and downloading without a build fetches the live one.
checksums returns the whole published digest set for one file rather than a single algorithm:
let checksums = try await client.database.checksums(id: "vpn_ip_v1", format: .mmdb)
print(checksums.sha256)downloads lists what your organization has fetched, newest first. Refusals are listed too, because a denial is what answers "it stopped working" and its absence answers nothing:
for attempt in try await client.database.downloads(limit: 20) {
print(attempt.created, attempt.datasetId, attempt.outcome, attempt.bytes ?? 0)
}Nothing here is cached, deliberately, and you should not cache it either: a listing belongs to the key that fetched it, and reusing one across keys will show an organization a catalog that is not its own.
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:
let client = InternetDataClient()
let device = try await client.oauth.deviceAuthorization(
clientID: "your-client-id", scope: "account.read apikeys.read apikeys.reveal",
)
print("Open \(device.verificationURI) and enter \(device.userCode)")
let token = try await client.oauth.pollDeviceToken(device, clientID: "your-client-id")
guard let apikey = token.apikey else {
fatalError("no API key came back: none was picked, or it can't be shown again")
}
let keyed = InternetDataClient(apiKey: apikey)A denied sign-in throws OauthError.accessDenied and a code that ran out OauthError.expiredToken. client.oauth.revoke(refreshToken, clientID: "your-client-id") 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.
An app that can take a browser redirect signs the person in there instead, with a PKCE pair made for that one sign-in:
let client = InternetDataClient()
let redirectURI = "http://127.0.0.1:8765/callback"
let pkce = client.oauth.createPkce()
let url = try client.oauth.authorizationURL(
clientID: "your-client-id", redirectURI: redirectURI, codeChallenge: pkce.challenge,
scope: "apikeys.use", state: "your-state",
)
// Open url in the browser. Its redirect to redirectURI carries code and state.
let token = try await client.oauth.exchangeAuthorizationCode(
code, clientID: "your-client-id", codeVerifier: pkce.verifier, redirectURI: 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.
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:
let client = InternetDataClient()
let registration = try await client.oauth.register(
redirectURIs: ["http://127.0.0.1:8765/callback"], 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.
The basics leave out isVpn, the proxy, hosting, CDN, bot, carrier, satellite, SSH, SMTP, web, DNS resolver and BitTorrent flags and the detail behind them, the company and the abuse contact, the Whois records and the paid members inside location and asn, such as location.city and asn.type; an answer to a key carries capReached, true once its organization's allowance is used and the answer has the basics (above). Every member an answer can leave out is Optional, where nil means "not in this answer" rather than "checked, and no". Since 4.0.0 that includes the eight flags isBot, isCarrier, isSatellite, isSsh, isSmtp, isWeb, isDnsResolver and isBittorrent, asn.type, company and abuse, which read false, "" and an empty object through 3.5.0. One the answer carries reads as served, and a null where the API allows none is still an answer the call cannot read.
result.isHosting ?? false // when you only want the flag
result.isHosting == nil // in the basics: not in this answer
result.location.city == nil // the same, inside a shared object
result.company == nil // no company in the answer, as in the basics
result.capReached == false // a key's answer with every field; a capped one threwA plan's tier, a database's standing and license type, a format, a download's outcome and a user agent's verdict are each a struct with a constant per value this release knows. From 3.0.0, a value the API adds later reads as itself rather than failing the call, so compare with == and keep a default: in a switch:
if database.standing == .licensed { /* download it */ }
database.standing.rawValue // "licensed", as the API spells it
database.standing.isKnown // false for a value added after this release
Database.Standing.known // every value this release knowsA format you pass in must be one of DatabaseFormat.known; any other is a badRequest before a request is made.
By default the library talks to the API over AsyncHTTPClient, configured to refuse redirects. Anything conforming to ClientTransport can take its place. To use URLSession on an Apple platform, add swift-openapi-urlsession to your own package and hand its transport in:
import OpenAPIURLSession
let client = InternetDataClient(options: .init(apiKey: key, transport: URLSessionTransport()))One thing to know if you do: the download endpoint answers 302, and the library follows that redirect itself as a second request rather than letting the transport do it. That is what keeps your API key off object storage, and it is what stops a whole database being read into memory before the library ever sees the link. Configure yours not to follow redirects. The library refuses such a response rather than reading it, but the transfer has already started by then.
Every request, object storage's included, names the library in its User-Agent (internetdata-swift/<version>), set before it reaches your transport, so a transport that wraps another can put its own name first.
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.
Geolocation, anonymity, ownership, network, service and domain data for any IP address, AS or domain, by API or as databases you download.
This project is licensed under the MIT License.