vpndetection

package module
v1.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 9, 2026 License: MIT Imports: 17 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

VPNDetection VPNDetection Go Client Library

Go Reference license

The official Go client library for the VPNDetection API.

The library helps you query VPNDetection's APIs for anonymity detection including VPNs, residential proxies, Tor nodes, hosting servers, CDNs, relays and more.

Getting Started

go get github.com/vpndetection-io/sdk-go

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

import vpndetection "github.com/vpndetection-io/sdk-go"

Usage

No API key needed to start. The free tier answers ip and is_vpn, and allows 1000 requests per day per source address.

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

result, err := client.Lookup(ctx, "45.83.91.1")
if err != nil {
    log.Fatal(err)
}
fmt.Println(result.IsVpn)   // true
With an API key

An API key raises your quota, and raises your features on a paid plan. Create one in the console, then pass it in:

client, err := vpndetection.New(vpndetection.WithAPIKey(os.Getenv("VPNDETECTION_API_KEY")))

result, err := client.Lookup(ctx, "45.83.91.1")
fmt.Println(result.IsVpn)               // true
fmt.Println(vpndetection.BoolValue(result.IsHosting))  // true

if vpn := result.Vpn; vpn != nil && vpn.Provider != nil {
    fmt.Println(*vpn.Provider)          // mullvad
}
Batch lookup

You can do batch lookups with a list, which parallelizes requests for you efficiently:

results, err := client.LookupBatch(ctx, []string{"45.83.91.1", "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: %v\n", ip, result.Result.IsVpn)
}

Results are keyed by address, so duplicates in your list collapse into a single request and one address failing never loses the rest.

Concurrency and other variables are configurable per-call:

results, err := client.LookupBatch(ctx, manyIPs,
    vpndetection.Concurrency(32), vpndetection.Retries(4))
Caching

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

client, err := vpndetection.New()

result, err := client.Lookup(ctx, "45.83.91.1")
fmt.Println(result.IsVpn)    // true, API request

result2, err := client.Lookup(ctx, "45.83.91.1")
fmt.Println(result2.IsVpn)   // true, 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 := vpndetection.New(vpndetection.WithCache(50_000, 6*time.Hour))
clientNoCache, err := vpndetection.New(vpndetection.WithoutCache())
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, err := client.Lookup(ctx, "192.168.1.1")
result.IsBogon   // true, this answer was computed rather than served
result.IsVpn     // 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:

vpndetection.IsBogon("10.0.0.1")   // true
Errors

Failures return a *vpndetection.Error carrying a Kind and a Retryable flag:

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

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

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. The library retries rate limits for you, but not if your quota is exceeded.

Database downloads

If your key carries the db.download scope, the licensed datasets are available through client.Database. DownloadFile fetches one to a path, streaming it straight to disk so that nothing bigger than a chunk is ever held in memory:

datasets, err := client.Database.List(ctx)

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

Or stream it into a writer of your own, take the time-limited link and run the transfer yourself, or take a small dataset as bytes:

written, err := client.Database.Download(ctx, "vpn_ip_extended_v1", vpndetection.FormatMMDB, w)
url, err := client.Database.DownloadURL(ctx, "vpn_ip_extended_v1", vpndetection.FormatMMDB)
raw, err := client.Database.DownloadBytes(ctx, "cdn_ip_v1", vpndetection.FormatCSVGZ)

DownloadBytes 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 use DownloadFile for anything you have not measured.

Absent is not false

Every field beyond IP and IsVpn is a pointer, because your plan decides which of them the API sends. A nil pointer means "not in your plan", not "checked, and no".

vpndetection.BoolValue(result.IsHosting)  // when you only want the flag
result.IsHosting == nil                   // not in your plan

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.

Documentation

Overview

Package vpndetection is the official Go client library for the VPNDetection API: anonymity detection covering VPNs, residential proxies, Tor nodes, hosting servers, CDNs and relays.

Start with New and Client.Lookup. No API key is needed: the free tier answers ip and is_vpn and allows 1000 requests per day per source address.

Index

Constants

View Source
const (
	LicenseTypeEvaluation   = api.Evaluation
	LicenseTypeStandard     = api.Standard
	LicenseTypeRedistribute = api.Redistribute
)
View Source
const (
	StandingExpired    = api.LicensedDatasetStandingExpired
	StandingLicensed   = api.LicensedDatasetStandingLicensed
	StandingUnlicensed = api.LicensedDatasetStandingUnlicensed
)
View Source
const (
	DownloadOutcomeOK           = api.DownloadOutcomeOk
	DownloadOutcomeUnauthorized = api.DownloadOutcomeUnauthorized
	DownloadOutcomeDenied       = api.DownloadOutcomeDenied
	DownloadOutcomeExpired      = api.DownloadOutcomeExpired
	DownloadOutcomeUnknown      = api.DownloadOutcomeUnknown
	DownloadOutcomeUnavailable  = api.DownloadOutcomeUnavailable
)
View Source
const DefaultBaseURL = "https://api.vpndetection.io"

DefaultBaseURL is the production API. Override it with WithBaseURL.

Variables

This section is empty.

Functions

func BoolValue

func BoolValue(v *bool) bool

BoolValue returns the value of the bool pointer passed in, or false if the pointer is nil.

Go has no `??`, so this is how a caller who only wants to know whether an address is flagged reads a tier-gated member: BoolValue(r.IsHosting). Read the pointer itself wherever absent and false must be told apart, which is the whole reason these are pointers. Same name and behaviour as stripe-go's helper of the same name, so it should already be familiar.

func IsBogon

func IsBogon(ip string) bool

IsBogon reports whether an address is private, loopback, link-local, documentation, multicast or otherwise not routable on the public internet, including the IPv6 equivalents and the 6to4 and Teredo ranges that wrap them.

These can never be VPN or proxy infrastructure, so the client answers them itself and they never cost a request. Client.IsBogon is the same check, for code that already holds a client.

Types

type BatchOption

type BatchOption interface {
	// contains filtered or unexported methods
}

BatchOption overrides a client default for one batch. Options that only mean something for a batch are BatchOption alone, so passing one to Lookup does not compile rather than being accepted and ignored.

func Concurrency

func Concurrency(n int) BatchOption

Concurrency overrides the client's in-flight request limit for this batch, so one large batch does not need a second client to widen it.

type BatchResult

type BatchResult struct {
	Result *Result
	Err    error
}

BatchResult is one address's outcome within a batch. Exactly one of Result and Err is set.

type Checksums

type Checksums struct {
	MD5    string `json:"md5,omitempty"`
	SHA1   string `json:"sha1,omitempty"`
	SHA256 string `json:"sha256,omitempty"`
	SHA512 string `json:"sha512,omitempty"`
}

Checksums of one published dataset file. A digest the exporter did not write is an empty string.

type ClassDetail

type ClassDetail = api.ClassDetail

The wire shapes a lookup answers with, re-exported so a consumer never has to name an internal package.

type Client

type Client struct {
	// Database is the licensed dataset downloads, for keys that carry the
	// db.download scope.
	Database *Database
	// contains filtered or unexported fields
}

Client is a client for the VPNDetection API. It is safe for concurrent use.

The cache is per instance and never global: two clients holding different API keys are on different plans and entitled to different fields, so a shared cache would serve one of them the other's shape.

func New

func New(opts ...Option) (*Client, error)

New builds a client. With no options it queries the production API on the free tier.

func (*Client) IsBogon

func (c *Client) IsBogon(ip string) bool

IsBogon reports whether an address is answered locally rather than served. Exposed here so the check is reachable from the client you already hold; the package-level IsBogon is the same function.

func (*Client) Lookup

func (c *Client) Lookup(ctx context.Context, ip string, opts ...LookupOption) (*Result, error)

Lookup classifies one address.

A bogon is answered locally and never reaches the network. Everything else is served, then cached for this client. Treat the answer as read only: repeat lookups of one address hand back the same cached pointers.

func (*Client) LookupBatch

func (c *Client) LookupBatch(
	ctx context.Context, ips []string, opts ...BatchOption,
) (map[string]BatchResult, error)

LookupBatch classifies many addresses concurrently.

The answers are keyed by address rather than positional, so duplicates in the input collapse to a single request and the caller never has to line two lists up. An address that fails carries its error as its value, so one bad entry cannot lose the rest of the answers. The returned error is reserved for the batch as a whole failing, which today means the context was canceled.

type Database

type Database struct {
	// contains filtered or unexported fields
}

Database is the licensed dataset downloads. Access is granted by contract rather than self-serve, and needs a key carrying the db.download scope.

func (*Database) Checksums

func (d *Database) Checksums(ctx context.Context, id string, format Format) (*Checksums, error)

Checksums are the digests of one published file, for verifying a download.

func (*Database) Download

func (d *Database) Download(
	ctx context.Context, id string, format Format, dst io.Writer,
) (int64, error)

Download streams one dataset file into dst and returns the bytes written.

Nothing beyond a single chunk is ever held in memory, whatever the dataset weighs. The transfer takes its deadline from ctx rather than from the HTTP client's Timeout, which would cap the whole body: 30 seconds is a sane bound on a lookup and the wrong one on a gigabyte.

A failure DURING the transfer is returned as it happened rather than wrapped in an *Error: a reset socket and a full disk are different problems, and only one of them is ours.

func (*Database) DownloadBytes

func (d *Database) DownloadBytes(ctx context.Context, id string, format Format) ([]byte, error)

DownloadBytes downloads one dataset file and hands back its bytes.

This holds the ENTIRE file in memory, and the catalog spans five orders of magnitude, from cdn_ip_v1 at 10 KB to resproxy_ip_90d_v1 at 1.79 GB, so reach for it at the small end and use Download or DownloadFile for anything you have not measured.

func (*Database) DownloadFile

func (d *Database) DownloadFile(
	ctx context.Context, id string, format Format, path string,
) (int64, error)

DownloadFile writes one dataset file to path and returns the bytes 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 dataset. Otherwise identical to Download.

func (*Database) DownloadURL

func (d *Database) DownloadURL(ctx context.Context, id string, format Format) (string, error)

DownloadURL is the time-limited URL for one dataset file.

The API answers 302 to object storage. The URL is returned rather than the bytes so the caller decides how to transfer a file that routinely runs to gigabytes; the link authorizes the START of a transfer, so one already running is not interrupted when it lapses.

func (*Database) Downloads

func (d *Database) Downloads(ctx context.Context, limit int) ([]Download, error)

Downloads is your organization's recent download attempts, newest first. A limit of zero or less takes the API's own default.

func (*Database) List

func (d *Database) List(ctx context.Context) ([]LicensedDataset, error)

List is the dataset families your organization is licensed to download. A license covers a family, while a download names one of its versions, so the ids Download and Checksums take come from LicensedDataset.Versions.

func (*Database) Metadata

func (d *Database) Metadata(ctx context.Context, id string) (*DatasetMetadata, error)

Metadata is what is inside one dataset: schema, samples, row count and sizes. It carries `updated` and `entries` without downloading anything, so poll it to decide whether today's build is worth fetching.

type DatasetFormatSize

type DatasetFormatSize = api.DatasetFormatSize

The dataset shapes, re-exported so a consumer never has to name an internal package.

type DatasetMetadata

type DatasetMetadata = api.DatasetMetadata

The dataset shapes, re-exported so a consumer never has to name an internal package.

type DatasetMetadataColumn

type DatasetMetadataColumn = api.DatasetMetadataColumn

The dataset shapes, re-exported so a consumer never has to name an internal package.

type Date

type Date = types.Date

Date is a calendar date with no time of day, as `last_seen` and `first_seen` carry.

type Download

type Download = api.Download

The dataset shapes, re-exported so a consumer never has to name an internal package.

type DownloadOutcome

type DownloadOutcome = api.DownloadOutcome

DownloadOutcome is how one download attempt ended.

type Error

type Error struct {
	Kind ErrorKind
	// Message is the API's own explanation, or a transport failure's text.
	Message string
	// StatusCode is the HTTP status, or 0 when no response was received.
	StatusCode int
	// RetryAfter is how long the server asked us to wait. Zero when it did not
	// ask, which on a 429 means an allowance is spent rather than throttled.
	RetryAfter time.Duration
	// contains filtered or unexported fields
}

Error is what every failure from this package unwraps to. Recover it with errors.As and branch on Kind.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Retryable

func (e *Error) Retryable() bool

Retryable reports whether retrying this exact request could succeed.

func (*Error) Unwrap

func (e *Error) Unwrap() error

type ErrorKind

type ErrorKind string

ErrorKind says why a request failed.

KindRateLimited and KindQuotaExceeded both arrive as HTTP 429 and are NOT the same thing. A rate limit is the API protecting itself, carries Retry-After, and retrying works. A spent quota carries no such header and retrying will not help until the window rolls over or the limit is raised. The header is the only thing that distinguishes them.

const (
	KindBadRequest    ErrorKind = "bad_request"
	KindUnauthorized  ErrorKind = "unauthorized"
	KindForbidden     ErrorKind = "forbidden"
	KindRateLimited   ErrorKind = "rate_limited"
	KindQuotaExceeded ErrorKind = "quota_exceeded"
	KindServerError   ErrorKind = "server_error"
	KindNetwork       ErrorKind = "network"
)

type Format

type Format string

Format is a format a dataset is published in. Not every dataset is built in every format: the _provider catalogs are keyed by provider id rather than by IP range, so no MMDB exists for them.

const (
	FormatCSVGZ Format = "csvgz"
	FormatMMDB  Format = "mmdb"
)

type LicenseType added in v1.2.0

type LicenseType = api.LicensedDatasetLicenseType

LicenseType is what a license permits you to do with the data.

type LicensedDataset

type LicensedDataset = api.LicensedDataset

The dataset shapes, re-exported so a consumer never has to name an internal package.

type LicensedVersion

type LicensedVersion = api.LicensedVersion

LicensedVersion is one published version of a licensed family. Its ID is what the download and checksum calls take.

type LookupOption

type LookupOption interface {
	BatchOption
	// contains filtered or unexported methods
}

LookupOption overrides a client default for one call. Every LookupOption works on a batch too.

func Retries

func Retries(n int) LookupOption

Retries overrides the client's retry count for this call.

type LookupResponse

type LookupResponse = api.LookupResponse

The wire shapes a lookup answers with, re-exported so a consumer never has to name an internal package.

type Option

type Option func(*config) error

Option configures a Client.

func WithAPIKey

func WithAPIKey(key string) Option

WithAPIKey authenticates as the key's organization. Which fields a lookup answers with, and how many requests are allowed, follow the key's plan.

func WithBaseURL

func WithBaseURL(rawURL string) Option

WithBaseURL points the client at a different deployment of the API.

func WithCache

func WithCache(size int, ttl time.Duration) Option

WithCache sizes the per-client answer cache. Defaults are 10000 addresses and a one hour TTL.

func WithConcurrency

func WithConcurrency(n int) Option

WithConcurrency sets how many requests a batch keeps in flight. Default 8.

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

WithHTTPClient supplies the HTTP client to send with, for a custom transport, proxy or timeout. Without it the SDK uses a client with a 30 second timeout.

The client is copied rather than mutated, and the copy adds a CheckRedirect that defers to yours (see Database.DownloadURL). A dataset transfer runs on a second copy with Timeout cleared, and is bounded by its context instead.

func WithRetries

func WithRetries(n int) Option

WithRetries sets how many further attempts a transient failure gets. Default 2.

func WithoutCache

func WithoutCache() Option

WithoutCache turns caching off, so every lookup of a non-bogon address is served.

type ProxyDetail

type ProxyDetail = api.ProxyDetail

The wire shapes a lookup answers with, re-exported so a consumer never has to name an internal package.

type Result

type Result struct {
	// The answer as it was served, with the wire's own optionality intact. Its
	// fields are promoted, so r.IsVpn and r.Vpn read straight off the Result.
	LookupResponse

	// True when this answer was computed locally rather than served, which
	// happens for a bogon and only for a bogon.
	IsBogon bool `json:"is_bogon"`
}

Result is what a lookup answers.

A pointer member is one your plan does not include. It never means "we could not check", so nil and false are genuinely different answers: nil is "not in your plan", false is "checked, and no". BoolValue collapses the two for callers who only want to know whether an address is flagged.

A detail object that is present but empty means the flag above it is false. A populated one always carries every one of its keys, empty values included.

type SampleFormat

type SampleFormat = api.LicensedVersionSampleFormats

SampleFormat is a format an evaluation sample is published in.

type Standing

type Standing = api.LicensedDatasetStanding

Standing is where a license stands: live, lapsed, or never bought.

type VpnDetail

type VpnDetail = api.VpnDetail

The wire shapes a lookup answers with, re-exported so a consumer never has to name an internal package.

Directories

Path Synopsis
internal
api
Package api provides primitives to interact with the openapi HTTP API.
Package api provides primitives to interact with the openapi HTTP API.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL