0.0
The project is in a healthy, maintained state
Query the VPNDetection API for anonymity detection including VPNs, residential proxies, Tor nodes, hosting servers, CDNs and relays.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
 Dependencies

Runtime

~> 1.1
~> 1.4
 Project Readme

VPNDetection VPNDetection Ruby Client Library

gem license

The official Ruby client library for the VPNDetection API.

It tells you whether an IP address is a VPN, residential proxy, Tor node, relay or hosting server.

Getting Started

gem install vpndetection

Or add it to your Gemfile:

gem 'vpndetection'

Requires Ruby 3.3 or newer, and libcurl at runtime, which the curl package brings on Debian and Alpine.

Usage

Lookups need no API key to try: the free plan answers each address's first lookups of the day without one, with ip, is_vpn, Tor and relay detection, is_anycast, hostname (the reverse DNS name), and country-level location and asn with the AS's country and RPKI status. A free API key answers your organization's first lookups each day with every field, and then the basics, without is_vpn, which raise :quota_exceeded (see Errors). The Data plan answers every field on every lookup.

require 'vpndetection'

client = VPNDetection::Client.new

begin
  result = client.lookup('45.83.91.1')
  result.is_vpn               # => true
  result.location['country']  # the ISO 3166 country code
  result.asn['name']          # who runs the announcing network
rescue VPNDetection::Error => e
  raise unless e.kind == :quota_exceeded && e.result

  # Your organization's lookups with every field are used: e.result has the basics.
  e.result.asn['name']
end

With an API key

A paid plan answers every field: is_hosting, is_cdn, is_bot (whether an automated client, such as a search engine's crawler, uses the address) and the four proxy flags as well, the AS's type, the carrier and satellite flags, the five service flags (SSH, SMTP, web, DNS resolver and BitTorrent), city-level location, the company and the abuse contact, bot (whose bot uses the address, what it does and whether its operator vouches for the address), and the provider (its ID and its name), confidence and last-seen detail behind each flag. Its quotas differ only in how many lookups they include, and a free key answers every field on your organization's first lookups each day. Create a key in the console, then pass it in:

client = VPNDetection::Client.new(api_key: ENV['VPNDETECTION_API_KEY'])

result = client.lookup('45.83.91.1')
result.is_vpn               # => true
result.is_hosting           # => true, on a paid plan
result.vpn['provider']      # => "nordvpn", on a paid plan

Your own address

result = client.my_ip
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 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.

Your plan and usage

acct = client.my_entitlement
acct.plan.name         # => "Data", what to show
acct.plan.key          # => "data_4", what to compare against
acct.usage.requests    # => 580
acct.usage.window_end  # => when the allowance resets

Usage counts against the anniversary of your subscription on a paid plan, not the calendar month and not the billing period, and on the free plan it counts the UTC day's lookups answered with every field; it is the same number a lookup is gated on. hard_limit is nil on an uncapped plan, which is not the same as zero.

Show plan.name and compare against plan.key: a plan's name can change, and its key never does. A value the API adds later to a plan's tier, a database's standing or license_type, a format or a download's outcome comes back as the string it served (from 5.16.0), so check for the values you know rather than assuming the list is complete.

Is that crawler who it says it is?

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 for the day) the answer says whose agent it names and whether this address bears that out:

result = client.lookup('66.249.66.1', user_agent: request.user_agent)
result.user_agent  # => {"agent"=>"Googlebot", "kind"=>"bot", "verdict"=>"verified"}

results = client.lookup_batch(ips, user_agents: { '66.249.66.1' => request.user_agent })

verdict is verified where the agent's operator vouches for the address, spoofed where it does not, unverifiable for a bot nothing published can confirm, and not_bot for a browser, an app or a script. my_ip takes user_agent: too. A batch's user_agents is keyed by each address as you list it, and an address with no agent, or an empty one, is looked up plainly. An answer with an agent is cached apart from the address's plain answer and from another agent's. The basics, a private address's and a lookup that sent none carry no user_agent (nil).

Batch lookup

Look up as many addresses as you like 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 = client.lookup_batch(['45.83.91.1', '8.8.8.8', '1.1.1.1'])

results.each do |ip, result|
  if result.is_a?(VPNDetection::Error)
    warn "#{ip}: #{result.message}"
    next
  end
  puts "#{ip}: #{result.is_vpn}"
end

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 entry answered with cap_reached true is its error too, the :quota_exceeded a lookup raises, with the entry's answer as result.

How many chunks are in flight at once, how many times a failed chunk is retried, and how long each chunk's request may take are configurable per call:

results = client.lookup_batch(many_ips, concurrency: 4, retries: 4, timeout: 5)

Caching

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

client = VPNDetection::Client.new

result = client.lookup('45.83.91.1')
result.is_vpn    # => true, API request

result2 = client.lookup('45.83.91.1')
result2.is_vpn   # => true, no API request, result was cached

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

client = VPNDetection::Client.new(cache_max_size: 50_000, cache_ttl: 6 * 60 * 60)
client_no_cache = VPNDetection::Client.new(cache: false)

An answer with cap_reached true is cached for a minute at most, because it can change as soon as the UTC day, the organization's plan or its cap does, and every call it answers raises :quota_exceeded again (see Errors).

Private and reserved addresses

Private, loopback, link-local, documentation and multicast addresses (and their IPv6 equivalents, including the 6to4 and Teredo ranges) can never be VPN or proxy infrastructure. The library answers them locally, so they cost no request and no quota:

result = client.lookup('192.168.1.1')
result.bogon?    # => true, this answer was computed rather than served
result.is_vpn    # => false

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

client.bogon?('10.0.0.1')   # => true
client.bogon?('8.8.8.8')    # => false

It is also on the module itself, if you want it without a client:

VPNDetection.bogon?('10.0.0.1')   # => true

Errors

Failures raise a VPNDetection::Error carrying a kind and a retryable? flag:

begin
  client.lookup('1.1.1.1')
rescue VPNDetection::Error => e
  warn "#{e.kind} #{e.retryable?}: #{e.message}"
end

kind is one of :bad_request, :unauthorized, :forbidden, :rate_limited, :quota_exceeded, :server_error or :network.

An answer with cap_reached true raises :quota_exceeded too, with retryable? false and status 200 (from 6.0.0). Your organization's lookups with every field are used, whether a free key's for the UTC day or a paid key's quota or overage cap, and the answer has the basics: the error's result is that answer, so a rescue still has them. A lookup, my_ip and every batch entry raise it, fresh or from the cache, it is never retried, and no option turns it off: rescue it to carry on. A private address and an answer to no key never raise it.

begin
  result = client.lookup('45.83.91.1')
rescue VPNDetection::Error => e
  raise unless e.kind == :quota_exceeded && e.result

  e.result.cap_reached   # => true
  e.result.is_vpn        # => nil, the basics have no is_vpn
end

Note that :rate_limited and :quota_exceeded both arrive as HTTP 429 and are not the same thing. A rate limit is when the API faces extreme traffic bursts and so retrying later works; but a spent quota needs your allowance raised or the window to roll over. A lookup with no key past its address's lookups for the day is a spent allowance too: it is sent once and raises :quota_exceeded with the API's own message, and a free API key answers past it. The library retries rate limits for you, but not if your quota is exceeded. It waits the Retry-After the API sent, or its own backoff from 250 ms when that's past about 24.8 days.

Timeouts and retries

client = VPNDetection::Client.new(timeout: 10, retries: 4)

result = client.lookup('45.83.91.1', timeout: 2, retries: 0)

timeout is in seconds and bounds each attempt, body included, so a call that is retried can take longer in total. It defaults to 30 seconds, and 0 means no bound; before 5.2.0 the default was 10, so pass timeout: 10 to keep that bound. The client's values are defaults: lookup, lookup_batch, my_ip and my_entitlement each take timeout: and retries: for that call alone, and every client.oauth method and every client.database call that is not a transfer takes timeout: (from 5.3.0). A database download bounds only its connection with it, because a whole transfer can take minutes. A negative value, anything that isn't a number, and anything past 2147483 seconds (the longest curl holds) raise ArgumentError where you pass them, before any request. So does a retries that isn't an Integer from 0 (from 5.11.3), and a concurrency that isn't an Integer from 1 given to Client.new, which lookup_batch refuses as :bad_request (from 5.11.4).

Database downloads

If your key carries the db.download scope, the licensed databases are available through client.database. A license covers a database FAMILY and a download names one of its versions, so the ID comes from versions:

family = client.database.list.first
id = family.versions.last.id

written = client.database.download(id, 'mmdb', './vpn_ip_extended_v1.mmdb')
url = client.database.download_url(id, 'mmdb')
bytes = client.database.download_bytes('cdn_ip_v1', 'csvgz')

download streams straight to disk, so nothing bigger than a chunk is ever held in memory whatever the database weighs, and it writes through a neighboring .part file so a transfer that dies half way leaves no truncated copy behind. download_url hands back the time-limited link and follows nothing, for when you want to run the transfer yourself. download_bytes holds the whole file in memory, and the catalog runs from cdn_ip_v1 at 10 KB to resproxy_ip_90d_v1 at 1.79 GB, so reach for download for anything you have not measured.

From 5.12.0, each of the three takes build:, the build a database.updated webhook names, so the file is the one whose sha256 the webhook carries rather than whatever is live by the time you ask. Without it you get the live build. A build is kept 7 days, and one pruned since is a :bad_request with status 410; a value that is no build's name raises ArgumentError before any request:

data = event.fetch('data') # a database.updated webhook's
client.database.download(data['dataset'], 'mmdb', "./#{data['dataset']}.mmdb", build: data['build'])

From 5.3.0, list, metadata, checksums, downloads and download_url each take timeout: in seconds for that call alone, overriding the client's for one attempt of it:

catalog = client.database.list(timeout: 5)
sums = client.database.checksums(id, 'mmdb', timeout: 5)

download and download_bytes deliberately take no timeout: and raise ArgumentError if handed one, rather than accepting it and quietly doing nothing: a transfer runs to gigabytes and minutes, so any bound that suits a JSON call would abandon a healthy download. download_url does take one, because minting the link is an ordinary API request - it bounds that request, not whatever you do with the link afterwards.

Sign in with OAuth (device flow)

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

client = VPNDetection::Client.new
device = client.oauth.device_authorization('your-client-id', scope: 'account.read apikeys.read apikeys.reveal')
puts "Open #{device.verification_uri} and enter #{device.user_code}"

token = client.oauth.poll_device_token('your-client-id', device)
raise 'no API key was picked' if token.apikey.nil?

keyed = VPNDetection::Client.new(api_key: token.apikey)

poll_device_token raises VPNDetection::OauthAccessDeniedError when the person refuses and VPNDetection::OauthExpiredTokenError when the code expires first. client.oauth.revoke('your-client-id', token.refresh_token) signs the machine out. 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 = VPNDetection::Client.new
redirect_uri = 'http://127.0.0.1:8765/callback'
pkce = client.oauth.create_pkce

url = client.oauth.authorization_url('your-client-id', redirect_uri, pkce.challenge,
                                     scope: 'apikeys.use', state: 'your-state')
# Open url in the browser. Its redirect to redirect_uri carries code and state.
token = client.oauth.exchange_authorization_code('your-client-id', code, pkce.verifier, redirect_uri)

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 client_id it gets back as the client ID for authorization_url and exchange_authorization_code:

client = VPNDetection::Client.new
registration = client.oauth.register(['http://127.0.0.1:8765/callback'], client_name: '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

A lookup with no key, and an answer past your organization's full answers (cap_reached true), leave out is_hosting, is_cdn, is_bot, the four proxy flags, the carrier, satellite and service flags, the AS's type (result.asn['type']), company and abuse, and of the detail behind each flag answer only Tor's and relay's. An answer to a key carries cap_reached, false while it has every field and true once your organization's allowance is used up (a free key's full answers for the UTC day, a paid key's quota or overage cap); it then leaves out is_vpn too, and raises :quota_exceeded with the answer as result. A field is present when the answer carries it and nil when it does not. nil means "not in this answer"; false means "we checked, and no".

result.hosting?                 # false when absent, for when you only want the flag
result.included?(:is_hosting)   # false when the answer leaves it out
result.included?(:is_vpn)       # false on a capped answer, where vpn? is false too
result.cap_reached == true      # only ever read off a rescued error's result

result.is_vpn is nil on a capped answer, and vpn? reads false then, which means "not in this answer", never "not a VPN".

Other Libraries

There are official VPNDetection client libraries available for many languages including PHP, Python, Go, Java, Ruby, and many popular frameworks such as Django, Rails, and Laravel. See our GitHub at https://github.com/vpndetection-io for more.

About VPNDetection

VPN Detection API: Accurate anonymity detection identifying VPNs, residential proxies, hosting servers, Tor nodes, CDNs, relays and more.

VPNDetection

License

This project is licensed under the MIT License.