ipdb

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 23 Imported by: ? modules, 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

go-ipdb

Self-contained IP database library for Go.

See also: go-domaindb

Automatically downloads and caches various types of IP databases for local in-process querying without reaching out to external APIs.

Supports the following operations:

  • Get ISO 3166 country code for IP address (geoIP)
  • Check if IP address is in a range database (such as Tor exit nodes or known VPNs)
  • Optional bring-your-own download logic
  • Optional bring-your-own caching logic

Requests for IP data do not leave your process, and you can aggregate multiple data sources into a single database for better accuracy.

Even if remote lists go down, the library can still function by using cached data. If you specify multiple data sources, the failing sources will be skipped and the remaining sources will be used.

Use Cases

This library is useful if:

  • You need to block non-human requests to parts of your application
  • You don't want to rely on an external service for IP data
  • You have strict privacy requirements that prevent using an external service for IP data
  • You need to aggregate multiple IP data sources into a single database

Download

Add to your project by running:

go get github.com/termermc/go-ipdb

Examples

See examples for more usage examples.

Below are some simpler examples demonstrating the basic usage of the library.

IP to Country

The IP to country system uses the MaxMindDB (.mmdb) format. By specifying a URL to a mirror of the MaxMind GeoLite2 database, your application can resolve the ISO 3166 country code of visitor IP addresses. A default must be provided for when the IP address's country is not known.

Both MaxMind's own schema (country.iso_code) and the flat schema used by many mirrors (country_code) are supported. If a source has multiple URLs, they are treated as mirrors and the first one that yields a valid database is used.

ip := netip.MustParseAddr("13.107.246.40")

// "AQ" (Antarctica) is returned if the country is not known.
cc, err := ipdb.ResolveIpIsoCountry(ip, "AQ")
if err != nil {
	panic(err)
}

println(cc) // US

IP Range Database Check

The IP range database check system uses newline-separated list(s) of IP ranges in CIDR notation or bare IP addresses. Any bare IP addresses will be assumed to be /32 for IPv4 and /128 for IPv6. Bare IPs and CIDR ranges can be mixed in the same list. Empty lines and lines prefixed with # are ignored.

All lists will be loaded into the in-memory database and IPs can be checked against them. Multiple lists can be combined for better detection.

// Assuming you have a DB named "tor-exit" containing Tor exit node IPs
const DbTorExit = "tor-exit"

ip := netip.MustParseAddr("13.107.246.40")

isTor, err := ipdb.IsIpInRangeDb(DbTorExit, ip)
if err != nil {
     panic(err)
}

if isTor {
	println("Tor exit node IP detected")
}

Obtaining Database Files

You can find many different IP lists online in .txt format for datacenter and VPN ranges. A few list URLs are included in the examples directory. Googling will yield more results. You should avoid any lists that are not updated frequently.

For Tor exit nodes, you can use Dan's exit node list. Keep in mind that this list rate limits you to 1 request per 30 minutes, so ensure you configure the Ipdb not to download faster than that. In general, you should be updating your databases every hour, or even less frequently.

MaxMind provides the free GeoLite2 database on their website, but you must agree to their terms of use and sign up before downloading it. There are public mirrors without this limitation online. You can Google "geolite2 country mmdb" to find them. A mirror URL from an NPM package is included in the examples directory.

Please keep in mind that the more lists you use, the more memory your process will consume. The in-memory representation of a database is larger than the database file itself.

Documentation

Index

Constants

View Source
const (
	// DefaultHttpTimeout is the default HTTP client's timeout for an entire download, including reading the body.
	// It is used as http.Client.Timeout when Options.HttpClient is nil.
	DefaultHttpTimeout = 5 * time.Minute

	// DefaultHttpResponseHeaderTimeout is the default HTTP client's timeout for receiving response headers after
	// sending a request.
	// It is used as http.Transport.ResponseHeaderTimeout when Options.HttpClient is nil.
	DefaultHttpResponseHeaderTimeout = 30 * time.Second
)
View Source
const DbNameGeoIpv4 = "__ipdb_geo_ipv4"

DbNameGeoIpv4 is the database name used for the GeoIP database for IPv4 addresses. Do not name any database with this name.

View Source
const DbNameGeoIpv6 = "__ipdb_geo_ipv6"

DbNameGeoIpv6 is the database name used for the GeoIP database for IPv6 addresses. Do not name any database with this name.

View Source
const DbNameMaxSize = 64

DbNameMaxSize is the max size of the database name, in bytes.

View Source
const DefaultMaxDatabaseSize int64 = 1 * 1024 * 1024 * 1024 // 1GiB

DefaultMaxDatabaseSize is the default maximum size of a single database, in bytes. See Options.MaxDatabaseSize.

Variables

View Source
var ErrAllUrlsFailed = errors.New("all URLs in data source failed")

ErrAllUrlsFailed is returned when all URLs in a data source failed.

View Source
var ErrDataSourceNoSource = errors.New("data source has no sources: len(Urls) == 0 or Get method is nil")

ErrDataSourceNoSource is returned when a data source has no sources. "No sources" means that the data source has no URLs and the Get method is nil.

View Source
var ErrDatabaseTooLarge = errors.New("database is too large")

ErrDatabaseTooLarge is returned when a database is larger than the maximum database size. See Options.MaxDatabaseSize.

View Source
var ErrDbNameTooLong = fmt.Errorf("database name too long, must be at most %d bytes long", DbNameMaxSize)

ErrDbNameTooLong is returned when a database name exceeds DbNameMaxSize bytes.

View Source
var ErrFailedByRetryPolicy = errors.New("database update was failed by the retry policy")

ErrFailedByRetryPolicy is returned when a database update was failed by the RetryPolicy returning RetryActionFail. The error also wraps the error of the source that failed.

View Source
var ErrInvalidDbName = errors.New("invalid database name")

ErrInvalidDbName is returned when a database name is empty, reserved or otherwise unusable.

View Source
var ErrInvalidRefreshInterval = errors.New("data source RefreshInterval must be positive")

ErrInvalidRefreshInterval is returned when a data source's RefreshInterval is not positive while downloading is enabled.

View Source
var ErrIpdbClosed = errors.New("ipdb closed")

ErrIpdbClosed is returned when an operation is attempted on a closed IP database.

View Source
var ErrNoCacheAndNoDownload = errors.New("no cached copy of database existed, and downloading is disabled")

ErrNoCacheAndNoDownload is returned when there is no cached database, and downloading is disabled so there is no way to get the database.

View Source
var ErrNoRanges = errors.New("range database contains no IP addresses or CIDR ranges")

ErrNoRanges is returned when a range database contains no IP addresses or CIDR ranges. A source that yields an empty list is treated as broken, rather than replacing existing data with nothing.

Functions

This section is empty.

Types

type AllCheckpoints

type AllCheckpoints struct {
	// All checkpoints.
	// Key is the database name, value is the checkpoint.
	Checkpoints map[string]Checkpoint `json:"checkpoints"`
}

AllCheckpoints is information for all database checkpoints.

type Checkpoint

type Checkpoint struct {
	// When the database was last updated from source.
	// Unix epoch second timestamp.
	LastUpdatedUnix int64 `json:"last_updated_unix"`
}

Checkpoint is checkpoint information for a database.

type DataSource

type DataSource struct {
	// Urls are the URLs where the IP data is located.
	// Either Get or Urls must be provided; Get takes precedence over Urls.
	//
	// For range databases, the contents of all URLs are merged into a single database.
	// URLs that fail to download or do not contain a valid list are handled by Options.RetryPolicy.
	// If Options.RetryPolicy is not set, the failed URL is logged and skipped, and the database is updated from the
	// remaining URLs.
	//
	// For geoIP databases, the URLs are mirrors that are tried in order; the first one that yields a valid database is
	// used.
	Urls []*url.URL

	// Get is a function to get the IP data.
	// Either Get or Urls must be provided; Get takes precedence over Urls.
	// The returned reader is closed by the Ipdb instance.
	//
	// Get should return within a reasonable amount of time; Ipdb.Close waits for running calls to finish.
	Get func() (io.ReadCloser, error)

	// RefreshInterval is the interval between updating the data from the source.
	// Required and must be positive, unless Options.DisableDownload is true.
	RefreshInterval time.Duration
}

DataSource stores source information for IP data. It includes the URLs the data can be fetched from and the time to wait between updating the data from them.

type DbNameValidator added in v1.1.0

type DbNameValidator interface {
	// ValidateDatabaseName returns an error if a database with the specified name cannot be stored.
	ValidateDatabaseName(name string) error
}

DbNameValidator can optionally be implemented by a StorageDriver to reject database names it cannot store. If implemented, NewIpdb validates all range database names with it and fails early if any are rejected.

type FsStorageDriver

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

FsStorageDriver implements StorageDriver by storing databases and checkpoints inside a data directory. Use NewFsStorageDriver to create an instance.

func NewFsStorageDriver

func NewFsStorageDriver(dataDir string) (*FsStorageDriver, error)

NewFsStorageDriver creates a new instance of StorageDriver. The specified directory must exist and be readable and writable by the current user. If the directory does not exist, returns an error matching fs.ErrNotExist (and syscall.ENOENT on Unix-like systems). If the path is not a directory, returns a wrapped syscall.ENOTDIR.

func (*FsStorageDriver) ReadCheckpoints

func (s *FsStorageDriver) ReadCheckpoints() (*AllCheckpoints, error)

func (*FsStorageDriver) ReadDatabase

func (s *FsStorageDriver) ReadDatabase(name string) (io.ReadCloser, error)

func (*FsStorageDriver) ValidateDatabaseName added in v1.1.0

func (s *FsStorageDriver) ValidateDatabaseName(name string) error

ValidateDatabaseName returns an error if a database with the specified name cannot be stored by the driver. If the name exceeds DbNameMaxSize bytes, returns ErrDbNameTooLong. If the name is empty or would collide with files used internally by the driver, returns a wrapped ErrInvalidDbName.

func (*FsStorageDriver) WriteCheckpoints

func (s *FsStorageDriver) WriteCheckpoints(checkpoints *AllCheckpoints) error

func (*FsStorageDriver) WriteDatabase

func (s *FsStorageDriver) WriteDatabase(name string, input io.ReadCloser) error

type HttpStatusError added in v1.1.0

type HttpStatusError struct {
	// The response status code.
	StatusCode int

	// The start of the response body, which may help explain the error.
	BodyPreview string
}

HttpStatusError is returned when downloading a source yields a response with a status code other than 200.

func (*HttpStatusError) Error added in v1.1.0

func (err *HttpStatusError) Error() string

type Ipdb

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

Ipdb stores and updates IP databases.

Includes functionality to:

  • Resolve ISO 3166 country codes for an IP address
  • Check if an IP address appears in a specific list of ranges (such as Tor exit nodes or datacenter ranges)

Databases are cached on disk and updated periodically from data sources. At runtime, databases are stored in-memory.

Caches are not aware of which data sources were used to create them, so adding, removing or changing data source URLs or Get method implementations should be followed by clearing the cache.

Create an instance with NewIpdb; do not create an empty Ipdb struct and attempt to use it.

There should only be one instance of Ipdb per storage driver or storage location, and ideally only one per process. It is safe to use a single instance of Ipdb across multiple goroutines.

func NewIpdb

func NewIpdb(options Options) (*Ipdb, error)

NewIpdb creates a new Ipdb instance. Blocks until the databases are loaded, unless Options.LoadDatabasesInBackground is true. If loading fails, returns the error, or with Options.LoadDatabasesInBackground, closes the returned instance. There should only be one instance of Ipdb per storage driver or storage location, and ideally only one per process. If error is nil, the returned Ipdb instance will never be nil.

func (*Ipdb) Close

func (s *Ipdb) Close() error

Close stops all background updates and frees all databases. Running downloads are canceled, and Close waits for background work to stop before returning. The Ipdb instance is no longer usable after closure; its methods return ErrIpdbClosed.

It is safe to call Close multiple times and from multiple goroutines. Subsequent calls do nothing. The returned error is currently always nil.

func (*Ipdb) DownloadAndLoadGeoIpv4Mmdb

func (s *Ipdb) DownloadAndLoadGeoIpv4Mmdb() error

DownloadAndLoadGeoIpv4Mmdb downloads the GeoIPv4 MMDB, loads it into memory and writes it to the cache. You most likely do not need to call this function, as loading databases is handled automatically by the Ipdb instance.

If the download fails or yields invalid data, the existing database is left untouched. If Options.GeoIpv4Source was nil, returns an error wrapping ErrDataSourceNoSource. If the Ipdb instance has been closed, returns ErrIpdbClosed.

func (*Ipdb) DownloadAndLoadGeoIpv6Mmdb

func (s *Ipdb) DownloadAndLoadGeoIpv6Mmdb() error

DownloadAndLoadGeoIpv6Mmdb downloads the GeoIPv6 MMDB, loads it into memory and writes it to the cache. You most likely do not need to call this function, as loading databases is handled automatically by the Ipdb instance.

If the download fails or yields invalid data, the existing database is left untouched. If Options.GeoIpv6Source was nil, returns an error wrapping ErrDataSourceNoSource. If the Ipdb instance has been closed, returns ErrIpdbClosed.

func (*Ipdb) DownloadAndLoadRangeDatabase added in v1.0.0

func (s *Ipdb) DownloadAndLoadRangeDatabase(name string) error

DownloadAndLoadRangeDatabase downloads the database with the specified name, loads it into memory and writes it to the cache. You most likely do not need to call this function, as loading databases is handled automatically by the Ipdb instance.

If the download fails or yields invalid data, the existing database is left untouched. If the database does not exist, returns a NoSuchDatabaseError. If the Ipdb instance has been closed, returns ErrIpdbClosed.

func (*Ipdb) IsIpInRangeDb added in v1.0.0

func (s *Ipdb) IsIpInRangeDb(dbName string, ip netip.Addr) (bool, error)

IsIpInRangeDb returns whether an IP was found in the specified IP range database. IPv4-mapped IPv6 addresses are treated as IPv4 addresses. If the database does not exist, returns a NoSuchDatabaseError. If the database has not been initialized, returns a NotInitializedError. If the Ipdb instance has been closed, returns ErrIpdbClosed.

func (*Ipdb) ResolveIpIsoCountry

func (s *Ipdb) ResolveIpIsoCountry(ip netip.Addr, defaultCc string) (string, error)

ResolveIpIsoCountry resolves the ISO 3166 country code for the specified IP address. The country code is uppercase. IPv4-mapped IPv6 addresses are treated as IPv4 addresses. If no country can be found, defaults to defaultCc. If the required database is not initialized, returns a NotInitializedError. If the Ipdb instance has been closed, returns ErrIpdbClosed.

To avoid returning an invalid ISO 3166 country code, the defaultCc parameter should ideally be a valid ISO 3166 country code. A good placeholder value is "AQ", which is the ISO 3166 country code for Antarctica.

type NoSuchDatabaseError added in v1.0.0

type NoSuchDatabaseError struct {
	// The name of database that did not exist.
	Name string
}

NoSuchDatabaseError is returned when trying to access a IP range database that does not exist. Includes the requested database name that did not exist.

func NewNoSuchDatabaseError added in v1.0.0

func NewNoSuchDatabaseError(name string) *NoSuchDatabaseError

NewNoSuchDatabaseError creates a new NoSuchDatabaseError instance with the specified database name.

func (*NoSuchDatabaseError) Error added in v1.0.0

func (err *NoSuchDatabaseError) Error() string

type NotInitializedError

type NotInitializedError struct {
	// The type of database that was not initialized.
	Name string

	// The message.
	Msg string
}

NotInitializedError is returned when a function is run that required an IP database to be initialized, but it was not initialized. Includes the IP database type that was required but not initialized.

func NewNotInitializedError

func NewNotInitializedError(name string, msg string) *NotInitializedError

NewNotInitializedError creates a new NotInitializedError instance with the specified database name and message.

func (*NotInitializedError) Error

func (err *NotInitializedError) Error() string

type Options

type Options struct {
	// The storage driver used to store cached databases and checkpoint information.
	// Unless you have a custom driver you want to use, you should most likely use FsStorageDriver.
	// Required.
	StorageDriver StorageDriver

	// By default, Ipdb uses slog.Default.
	// If Logger is specified, it will use it instead.
	Logger *slog.Logger

	// Overrides the default HTTP client if not nil.
	// If nil, uses a default HTTP client based on http.DefaultTransport, with a timeout of DefaultHttpTimeout per
	// download and a timeout of DefaultHttpResponseHeaderTimeout for receiving response headers.
	HttpClient *http.Client

	// If true, disables downloading from sources and only uses cached database files.
	//
	// Important: You must still provide sources for the databases you want to use, regardless of whether download is
	// disabled.
	DisableDownload bool

	// If true, NewIpdb returns without waiting for databases to be loaded, and they are loaded in the background instead.
	//
	// This option is intended for speeding up startup during development, where waiting for databases to load or
	// download every time the program starts gets in the way. It is unsuitable for production, because:
	//   - Any methods on Ipdb that require databases return a NotInitializedError until the databases have loaded.
	//   - If loading fails, the error is only logged, and the Ipdb instance is closed. Loading is not retried, and
	//     the instance's methods return ErrIpdbClosed from then on. Without this option, NewIpdb would instead
	//     return the error, so the program can handle it.
	LoadDatabasesInBackground bool

	// The maximum size of a single database, in bytes.
	// Downloads and cached files larger than this are rejected with ErrDatabaseTooLarge.
	// For range databases with multiple URLs, the limit applies to the merged database.
	// If zero or negative, DefaultMaxDatabaseSize is used.
	MaxDatabaseSize int64

	// Decides what happens when a source of a database fails to download: retry it, skip it, or fail the update of the
	// whole database.
	// See RetryPolicy.
	// A download that completes but does not contain a valid database also counts as a failure.
	//
	// If nil, failed sources are logged and skipped without retrying, so a broken URL never stops a database
	// from being updated from its other URLs.
	// See SkipAllSources.
	RetryPolicy RetryPolicy

	// A mapping of database names to their underlying IP range sources.
	// Each source must yield a newline-separated list of IP addresses and/or CIDR ranges.
	// Empty lines and lines that start with "#" are ignored.
	//
	// Names must not be empty, must be at most DbNameMaxSize bytes long, and must not be DbNameGeoIpv4 or
	// DbNameGeoIpv6. The storage driver may impose additional restrictions.
	RangeSources map[string]*DataSource

	// The source for the IPv4 country database.
	// It must yield a MaxMindDB (.mmdb) file that stores the ISO 3166 country code in either a top-level "country_code"
	// field (as used by many third-party mirrors) or in "country.iso_code" (as used by MaxMind's GeoLite2 and GeoIP2
	// databases).
	// See: https://dev.maxmind.com/geoip/geolite2-free-geolocation-data/
	//
	// Resolving IPv4 country codes will be disabled if this field is nil.
	GeoIpv4Source *DataSource

	// The source for the IPv6 country database.
	// It must yield a MaxMindDB (.mmdb) file that stores the ISO 3166 country code in either a top-level "country_code"
	// field (as used by many third-party mirrors) or in "country.iso_code" (as used by MaxMind's GeoLite2 and GeoIP2
	// databases).
	// See: https://dev.maxmind.com/geoip/geolite2-free-geolocation-data/
	//
	// Resolving IPv6 country codes will be disabled if this field is nil.
	GeoIpv6Source *DataSource
}

Options are options for creating an Ipdb instance. Any omitted DataSource fields will be disabled and unavailable, even if cached files for them exist.

type RetryAction added in v1.1.0

type RetryAction int

RetryAction is the action to take after a source fails to download.

const (
	// RetryActionSkip gives up on the source for the current update.
	//
	// For range databases with multiple URLs, the database is updated from the remaining URLs,
	// and the ranges from the skipped URL are left out until it works again.
	// For geoIP databases with multiple URLs, the next mirror is tried.
	// If every source of a database is skipped, the update fails and the database keeps its current data.
	//
	// This is the zero value, and what happens if Options.RetryPolicy is nil.
	RetryActionSkip RetryAction = iota

	// RetryActionRetry tries to download the source again after RetryDecision.Delay.
	RetryActionRetry

	// RetryActionFail fails the update of the whole database immediately, without trying its remaining sources.
	// The database keeps its current data, and the update is retried later as for any other failed update.
	RetryActionFail
)

func (RetryAction) String added in v1.1.0

func (a RetryAction) String() string

type RetryDecision added in v1.1.0

type RetryDecision struct {
	// Action is the action to take.
	// Unknown actions are treated as RetryActionSkip.
	Action RetryAction

	// Delay is the time to wait before retrying when Action is RetryActionRetry.
	// The wait is cut short if the Ipdb instance is closed.
	// Ignored for other actions.
	Delay time.Duration
}

RetryDecision is returned by a RetryPolicy to decide what happens after a source fails to download.

func SkipAllSources added in v1.1.0

func SkipAllSources(_ SourceFailure) RetryDecision

SkipAllSources is the default RetryPolicy. It skips any failed sources without retrying.

type RetryPolicy added in v1.1.0

type RetryPolicy func(failure SourceFailure) RetryDecision

RetryPolicy decides what happens when a source of a database fails to download. It is called once for each failed attempt, and may be called concurrently for different databases.

Retries made by the policy all happen within a single update. They are separate from the retries of failed updates, which happen with an increasing delay that never exceeds the database's DataSource.RefreshInterval.

Example policy that retries server errors twice, and skips anything else (such as a 404):

func(f ipdb.SourceFailure) ipdb.RetryDecision {
	statusErr, is := errors.AsType[*ipdb.HttpStatusError](f.Err)
	if is && statusErr.StatusCode >= 500 && f.Attempt <= 2 {
		return ipdb.RetryDecision{
			Action: ipdb.RetryActionRetry,
			Delay: 10 * time.Second,
		}
	}
	return ipdb.RetryDecision{
		Action: ipdb.RetryActionSkip,
	}
}

type SourceFailure added in v1.1.0

type SourceFailure struct {
	// DbName is the name of the database being updated.
	// This is either a range database name, DbNameGeoIpv4 or DbNameGeoIpv6.
	DbName string

	// Url is the URL that failed, or nil if the source is a DataSource.Get function.
	// It may contain credentials or query parameters such as license keys, so take care when logging it.
	Url *url.URL

	// Attempt is the number of attempts made to download this source during the current update, starting at 1.
	Attempt int

	// Err is the error that caused the attempt to fail.
	// A response with a non-200 status code produces an error that matches *HttpStatusError when checked with errors.As.
	// A download that is not a valid database produces an error that matches ErrNoRanges, ErrDatabaseTooLarge or
	// a parse error, depending on the problem.
	Err error
}

SourceFailure describes a failed attempt to download one source of a database.

type StorageDriver

type StorageDriver interface {
	// WriteDatabase writes the contents of the reader to the database file with the specified name.
	// The reader will be closed by the function regardless of whether an error occurs.
	// If an error occurs, any previously written database with the same name must be left intact.
	// May be called concurrently for different names.
	WriteDatabase(name string, input io.ReadCloser) error

	// ReadDatabase opens the database file with the specified name for reading.
	// The caller is expected to close the reader.
	// If there is no cached database with the specified name, the function must return an error that matches
	// fs.ErrNotExist when checked with errors.Is (such as syscall.ENOENT or a wrapped error from the os package).
	ReadDatabase(name string) (io.ReadCloser, error)

	// WriteCheckpoints writes all checkpoints.
	// Checkpoints must not be nil.
	WriteCheckpoints(checkpoints *AllCheckpoints) error

	// ReadCheckpoints reads and returns all checkpoints.
	// The returned checkpoints will never be nil if there is no error.
	// If checkpoints have not been saved yet, the function must return an error that matches
	// fs.ErrNotExist when checked with errors.Is (such as syscall.ENOENT or a wrapped error from the os package).
	ReadCheckpoints() (*AllCheckpoints, error)
}

StorageDriver is an interface that stores IP databases and checkpoint data.

Directories

Path Synopsis
examples
simple command

Jump to

Keyboard shortcuts

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