ip2x

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2022 License: MIT Imports: 7 Imported by: 4

README

ip2x

Go Reference

Module ip2x is an idiomatic, efficient, and robust library and command-line tool for querying IP2Location databases.

Compared to github.com/ip2location/ip2location-go/v9 and github.com/ip2location/ip2proxy-go/v3, this library:

  • Is written in idiomatic Go.
  • Is faster and has fewer allocations.
  • Only reads individual fields as requested.
  • Has more flexible type-independent getters.
  • Supports directly querying a net/netip.Addr.
  • Exposes database metadata including version, product, available fields, and supported IP versions.
  • Handles all errors correctly.
  • Uses errors and zero values correctly instead of using arbitrary strings in field values.
  • Supports pretty-printing database records as text (optionally colored and/or multiline).
  • Supports encoding database records as JSON.
  • Unifies the interface for both databases.
  • Has field documentation comments.
  • Uses code generation to reduce code duplication and potential bugs.

CLI

ip2x db_path [ip_addr...]
  -compact
        compact output
  -json
        use json output
  -strict
        fail immediately if a record is not found
$ ip2x IP2LOCATION-LITE-DB11.IPV6.BIN 1.1.1.1
IP2Location<DB11>{
  city "Los Angeles"
  country_code "US"
  country_name "United States of America"
  latitude 34.05286
  longitude -118.24357
  region "California"
  time_zone "-07:00"
  zip_code "90001"
}

Library

package main

import (
	"fmt"
	"os"

	"github.com/pg9182/ip2x"
)

func main() {
	f, err := os.Open("IP2LOCATION-LITE-DB11.IPV6.BIN")
	if err != nil {
		panic(err)
	}
	defer f.Close()

	db, err := ip2x.New(f)
	if err != nil {
		panic(err)
	}

	fmt.Println(db)
	fmt.Println()

	r, err := db.LookupString("8.8.8.8")
	if err != nil {
		panic(err)
	}

	// pretty-print
	fmt.Println(r.FormatString(true, true))
	fmt.Println()

	// get some fields the easy way
	fmt.Println("Test:", r.Get(ip2x.CountryCode), r.Get(ip2x.Region))

	// get the latitude
	{
		fmt.Println()
		fmt.Printf("Get(Latitude): %#v\n", r.Get(ip2x.Latitude))

		latstr, ok := r.GetString(ip2x.Latitude)
		fmt.Printf("GetString(Latitude): %#v, %#v\n", latstr, ok)

		latflt, ok := r.GetFloat32(ip2x.Latitude)
		fmt.Printf("GetFloat32(Latitude): %#v, %#v\n", latflt, ok)
	}

	// get an unsupported field
	{
		fmt.Println()
		fmt.Printf("Get(ISP): %#v\n", r.Get(ip2x.ISP))

		ispstr, ok := r.GetString(ip2x.ISP)
		fmt.Printf("GetString(ISP): %#v, %#v\n", ispstr, ok)

		ispflt, ok := r.GetString(ip2x.ISP)
		fmt.Printf("GetString(ISP): %#v, %#v\n", ispflt, ok)
	}
}
Output:
IP2Location 2022-10-29 DB11 [city,country_code,country_name,latitude,longitude,region,time_zone,zip_code] (IPv4+IPv6)

IP2Location<DB11>{
  city "Mountain View"
  country_code "US"
  country_name "United States of America"
  latitude 37.40599
  longitude -122.078514
  region "California"
  time_zone "-07:00"
  zip_code "94043"
}

Test: US California

Get(Latitude): 37.40599
GetString(Latitude): "37.40599", true
GetFloat32(Latitude): 37.40599, true

Get(ISP): <nil>
GetString(ISP): "", false
GetString(ISP): "", false

Documentation

Overview

Package ip2x reads IP2Location binary databases.

Index

Constants

This section is empty.

Variables

View Source
var (
	RecordStringColor     = false
	RecordStringMultiline = false
)

Default options for Record.String.

Functions

This section is empty.

Types

type DB

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

DB reads an IP2Location binary database.

func New

func New(r io.ReaderAt) (*DB, error)

New opens an IP2Location binary database reading from r.

func (*DB) EachField

func (db *DB) EachField(fn func(DBField) bool)

EachField calls fn for each column in the database until fn returns false.

func (*DB) Has

func (db *DB) Has(f DBField) bool

Has returns true if the database contains f.

func (*DB) HasIPv4

func (db *DB) HasIPv4() bool

HasIPv4 returns true if the database contains IPv4 entries.

func (*DB) HasIPv6

func (db *DB) HasIPv6() bool

HasIPv6 returns true if the database contains HasIPv6 entries.

func (*DB) Info

func (db *DB) Info() (DBProduct, DBType)

Info returns the database product and type.

func (*DB) Lookup

func (db *DB) Lookup(a netip.Addr) (r Record, err error)

Lookup looks up a in db. If a is not found, an empty record and nil error is returned. If an i/o error occurs, an empty record and non-nil error is returned.

func (*DB) LookupString

func (db *DB) LookupString(ip string) (r Record, err error)

LookupString parses and looks up a in db. If a parse error occurs, an empty record and nil error is returned. To catch parse errors, parse it separately using net/netip.ParseAddr, and pass it to DB.Lookup.

func (*DB) String

func (db *DB) String() string

String returns a human-readable string describing the database.

func (*DB) Version

func (db *DB) Version() string

Version returns the database version.

type DBField

type DBField int

DBField represents a database column.

const AS DBField = 3

Autonomous system number (ASN).

const ASN DBField = 4

Autonomous system (AS) name.

const AddressType DBField = 1

IP address types as defined in Internet Protocol version 4 (IPv4) and Internet Protocol version 6 (IPv6).

  • (A) Anycast - One to the closest
  • (U) Unicast - One to one
  • (M) Multicast - One to multiple
  • (B) Broadcast - One to all
const AreaCode DBField = 2

A varying length number assigned to geographic areas for call between cities.

See https://www.ip2location.com/area-code-coverage.

const Category DBField = 5

The domain category is based on IAB Tech Lab Content Taxonomy.

These categories are comprised of Tier-1 and Tier-2 (if available) level categories widely used in services like advertising, Internet security and filtering appliances.

See https://www.ip2location.com/free/iab-categories.

const City DBField = 6

City name.

const CountryCode DBField = 7

Two-character country code based on ISO 3166.

const CountryName DBField = 8

Country name based on ISO 3166.

const Domain DBField = 9

Internet domain name associated with IP address range.

const Elevation DBField = 10

Average height of city above sea level in meters (m).

const IDDCode DBField = 11

The IDD prefix to call the city from another country.

const ISP DBField = 12

Internet Service Provider or company's name.

const LastSeen DBField = 13

Proxy last seen in days.

const Latitude DBField = 14

City latitude. Defaults to capital city latitude if city is unknown.

const Longitude DBField = 15

City longitude. Defaults to capital city longitude if city is unknown.

const MCC DBField = 16

Mobile Country Codes (MCC) as defined in ITU E.212 for use in identifying mobile stations in wireless telephone networks, particularly GSM and UMTS networks.

const MNC DBField = 17

Mobile Network Code (MNC) is used in combination with a Mobile Country Code (MCC) to uniquely identify a mobile phone operator or carrier.

const MobileBrand DBField = 18

Commercial brand associated with the mobile carrier.

See https://www.ip2location.com/mobile-carrier-coverage.

const NetSpeed DBField = 19

Internet Connection Type

  • (DIAL) dial up
  • (DSL) broadband/cable/fiber/mobile
  • (COMP) company/T1
const Provider DBField = 20

Name of VPN provider if available.

const ProxyType DBField = 21

Type of proxy.

  • (VPN) Anonymizing VPN services. These services offer users a publicly accessible VPN for the purpose of hiding their IP address. Anonymity: High.
  • (TOR) Tor Exit Nodes. The Tor Project is an open network used by those who wish to maintain anonymity. Anonymity: High.
  • (DCH) Hosting Provider, Data Center or Content Delivery Network. Since hosting providers and data centers can serve to provide anonymity, the Anonymous IP database flags IP addresses associated with them. Anonymity: Low.
  • (PUB) Public Proxies. These are services which make connection requests on a user's behalf. Proxy server software can be configured by the administrator to listen on some specified port. These differ from VPNs in that the proxies usually have limited functions compare to VPNs. Anonymity: High.
  • (WEB) Web Proxies. These are web services which make web requests on a user's behalf. These differ from VPNs or Public Proxies in that they are simple web-based proxies rather than operating at the IP address and other ports level. Anonymity: High.
  • (SES) Search Engine Robots. These are services which perform crawling or scraping to a website, such as, the search engine spider or bots engine. Anonymity: Low.
  • (RES) Residential proxies. These services offer users proxy connections through residential ISP with or without consents of peers to share their idle resources. Only available with PX10 & PX11. Anonymity: Medium.
const Region DBField = 22

Region or state name.

const Threat DBField = 23

Security threat reported.

  • (SPAM) Email and forum spammers
  • (SCANNER) Network security scanners
  • (BOTNET) Malware infected devices
const Timezone DBField = 24

UTC time zone (with DST supported).

const UsageType DBField = 25

Usage type classification of ISP or company.

  • (COM) Commercial
  • (ORG) Organization
  • (GOV) Government
  • (MIL) Military
  • (EDU) University/College/School
  • (LIB) Library
  • (CDN) Content Delivery Network
  • (ISP) Fixed Line ISP
  • (MOB) Mobile ISP
  • (DCH) Data Center/Web Hosting/Transit
  • (SES) Search Engine Spider
  • (RSV) Reserved
const WeatherStationCode DBField = 26

The special code to identify the nearest weather observation station.

const WeatherStationName DBField = 27

The name of the nearest weather observation station.

const Zipcode DBField = 28

ZIP code or Postal code.

See https://www.ip2location.com/zip-code-coverage.

func (DBField) GoString

func (f DBField) GoString() string

GoString returns the Go name of the field.

func (DBField) String

func (f DBField) String() string

String returns the name of the database column.

type DBProduct

type DBProduct uint8

DBProduct represents an IP2Location database product.

const IP2Location DBProduct = 1

IP2Location™ IP Address Geolocation Database provides a solution to deduce the geolocation of a device connected to the Internet and to determine the approximate geographic location of an IP address along with some other useful information like country, region or state, city, latitude and longitude, ZIP/Postal code, time zone, Internet Service Provider (ISP) or company name, domain name, net speed, area code, weather station code, weather station name, mobile country code (MCC), mobile network code (MNC) and carrier brand, elevation, usage type, address type and advertising category.

const IP2Proxy DBProduct = 2

IP2Proxy™ Proxy Detection Database contains IP addresses which are used as VPN anonymizer, open proxies, web proxies and Tor exits, data center, web hosting (DCH) range, search engine robots (SES) and residential proxies (RES).

func (DBProduct) FormatProduct

func (p DBProduct) FormatProduct(t DBType) string

FormatProduct returns the full product name of t.

func (DBProduct) FormatType

func (p DBProduct) FormatType(t DBType) string

FormatType prepends the product prefix to t.

func (DBProduct) GoString

func (p DBProduct) GoString() string

GoString returns the Go name of the product.

func (DBProduct) String

func (p DBProduct) String() string

String returns the name of the product.

func (DBProduct) SupportsType

func (p DBProduct) SupportsType(t DBType) bool

SupportsType returns true if p supports variant t.

type DBType

type DBType uint8

DBType represents an IP2Location database variant. Each database type contains different sets of columns.

func (DBType) String

func (t DBType) String() string

String formats the type as a string.

type Record

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

Record points to a database row.

func (Record) FormatString

func (r Record) FormatString(color, multiline bool) string

FormatString gets and formats all fields in the record as a human-readable string. Note that this is highly inefficient.

func (Record) Get

func (r Record) Get(f DBField) any

Get gets f as the default type. If an error occurs or the field is not present, nil is returned. This is slightly less efficient than the more specific getters.

func (Record) GetFloat32

func (r Record) GetFloat32(f DBField) (float32, bool)

GetFloat32 gets f as a float32, if possible.

func (Record) GetString

func (r Record) GetString(f DBField) (string, bool)

GetString gets f as a string.

func (Record) IsValid

func (r Record) IsValid() bool

IsValid checks whether the record is pointing to a database row.

func (Record) MarshalJSON

func (r Record) MarshalJSON() ([]byte, error)

MarshalJSON encodes the record as JSON.

func (Record) String

func (r Record) String() string

String gets and formats all fields in the record as a human-readable string. Note that this is highly inefficient.

Directories

Path Synopsis
cmd
ip2x command
Command ip2x queries an IP2Location binary database.
Command ip2x queries an IP2Location binary database.
test module

Jump to

Keyboard shortcuts

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