ip2location-go

repository·master·Indexed 20 days ago

https://github.com/ip2location/ip2location-go

A high-performance Go package for performing IPv4 and IPv6 IP-to-location lookups using IP2Location file-based BIN and CSV databases. It provides extensive metadata including geography (country, region, city), network/ISP (ASN, domain), and mobile/telecom information. The library includes the IP2Location class for BIN database queries, the Country and Region classes for CSV lookups, and IPTools for IP validation, conversion, and CIDR manipulation.

Tokens
12.1K
Snippets
27
Records
41
Agent score
67%

What's inside ip2location-go

  1. Overview of IP2Location Go Package

    master

    The ip2location-go package provides high-performance IP address lookups using IP2Location file-based databases. It supports both IPv4 and IPv6 and can extract a wide range of metadata from an IP address, including:

    • Geography: Country, region, city, latitude, longitude, ZIP code, district.
    • Network/ISP: ISP, domain name, connection type, Autonomous System Number (ASN), Autonomous System (AS), AS domain, AS usage type, and AS CIDR.
    • Mobile/Telecom: MCC, MNC, mobile brand, IDD code, area code.
    • Other: Time zone, weather station code, station name, elevation, usage type, address type, and IAB category.

    This package is suitable for use cases such as selecting geographically closest mirrors, analyzing web server logs, fraud detection, software export controls, and geotargeting.

  2. Overview of the IP2Location Go Package

    master

    The ip2location-go package enables high-speed IP address lookups using IP2Location file-based databases. It supports both IPv4 and IPv6 addresses and can extract a wide range of metadata including country, region, city, latitude, longitude, ZIP code, time zone, ISP, domain name, connection type, ASN, and more.

    Common use cases include:

    • Geographically selecting the closest mirror.
    • Analyzing web server logs for visitor demographics.
    • Credit card fraud detection.
    • Software export controls.
    • Displaying native language and currency.
    • Preventing password sharing and service abuse.
    • Geotargeting in advertisements.
  3. Configure IP2Location BIN database dependencies

    master

    The library requires an IP2Location BIN database to function. You can obtain databases from:

    Choosing between IPv4 and IPv6 BIN files:

    • Use the IPv4 BIN file if you only need to query IPv4 addresses.
    • Use the IPv6 BIN file if you need to query both IPv4 and IPv6 addresses.
  4. Implement the DBReader interface

    master

    If you need to load the IP2Location database from a source other than a standard file (e.g., an in-memory buffer, a network stream, or a custom encrypted filesystem), you can implement the DBReader interface and pass it to OpenDBWithReader.

    To be compatible, your type must implement:

    • io.ReadCloser: To allow the package to close the source when the DB is closed.
    • io.ReaderAt: To allow random access reading of the database file.
    type MyCustomReader struct {
        // implementation
    }
    
    func (m *MyCustomReader) ReadAt(p []byte, off int64) (n int, err error) { /* ... */ }
    func (m *MyCustomReader) Close() error { /* ... */ }
    
    // Usage
    reader := &MyCustomReader{}
    db, err := ip2location.OpenDBWithReader(reader)
  5. Initialize IPTools with OpenTools()

    master

    To use the IP address manipulation and validation utilities, you must first initialize an IPTools instance using the OpenTools() function. This function sets up the necessary internal ranges for IPv4 and IPv6 calculations.

    Returns a pointer to an IPTools struct.

    package main
    
    import "github.com/ip2location/ip2location-go/v9"
    
    func main() {
        tools := ip2location.OpenTools()
        // Use tools for IP manipulation
        _ = tools
    }
  6. Open an IP2Location database

    master

    To use the IP2Location database in Go, you can open a .BIN file using OpenDB or OpenDBWithReader.

    • OpenDB(dbpath string): Opens a database file from a provided file path.
    • OpenDBWithReader(reader DBReader): Opens a database using an object that implements the DBReader interface (which requires io.ReadCloser and io.ReaderAt). This is useful for reading from memory or custom storage.

    Note: The package also provides a deprecated Open(dbpath string) function that sets a global defaultDB instance. It is recommended to use the DB object returned by OpenDB for better control.

    package main
    
    import (
    	"fmt"
    	"github.com/ip2location/ip2location-go/v9"
    )
    
    func main() {
    	db, err := ip2location.OpenDB("IP2LOCATION-LITE-IP-COUNTRY.BIN")
    	if err != nil {
    		panic(err)
    	}
    	defer db.Close()
    
    	record, err := db.Get_all("8.8.8.8")
    	if err != nil {
    		panic(err)
    	}
    	fmt.Printf("Country: %s\n", record.Country_long)
    }
  7. Query geolocation information from a BIN database

    master

    Use ip2location.OpenDB(path) to load a BIN database and db.Get_all(ip) to retrieve comprehensive geolocation data for a specific IP address. Remember to call db.Close() when finished to release resources.

    package main
    
    import (
    	"fmt"
    	"github.com/ip2location/ip2location-go/v9"
    )
    
    func main() {
    	db, err := ip2location.OpenDB("./IP-COUNTRY-REGION-CITY-LATITUDE-LONGITUDE-ZIPCODE-TIMEZONE-ISP-DOMAIN-NETSPEED-AREACODE-WEATHER-MOBILE-ELEVATION-USAGETYPE-ADDRESSTYPE-CATEGORY-DISTRICT-ASN.BIN")
    	
    	if err != nil {
    		fmt.Print(err)
    		return
    	}
    	ip := "8.8.8.8"
    	results, err := db.Get_all(ip)
    	
    	if err != nil {
    		fmt.Print(err)
    		return
    	}
    	
    	fmt.Printf("country_short: %s\n", results.Country_short)
    	fmt.Printf("country_long: %s\n", results.Country_long)
    	fmt.Printf("region: %s\n", results.Region)
    	fmt.Printf("city: %s\n", results.City)
    	fmt.Printf("isp: %s\n", results.Isp)
    	fmt.Printf("latitude: %f\n", results.Latitude)
    	fmt.Printf("longitude: %f\n", results.Longitude)
    	fmt.Printf("domain: %s\n", results.Domain)
    	fmt.Printf("zipcode: %s\n", results.Zipcode)
    	fmt.Printf("timezone: %s\n", results.Timezone)
    	fmt.Printf("netspeed: %s\n", results.Netspeed)
    	fmt.Printf("iddcode: %s\n", results.Iddcode)
    	fmt.Printf("areacode: %s\n", results.Areacode)
    	fmt.Printf("weatherstationcode: %s\n", results.Weatherstationcode)
    	fmt.Printf("weatherstationname: %s\n", results.Weatherstationname)
    	fmt.Printf("mcc: %s\n", results.Mcc)
    	fmt.Printf("mnc: %s\n", results.Mnc)
    	fmt.Printf("mobilebrand: %s\n", results.Mobilebrand)
    	fmt.Printf("elevation: %f\n", results.Elevation)
    	fmt.Printf("usagetype: %s\n", results.Usagetype)
    	fmt.Printf("addresstype: %s\n", results.Addresstype)
    	fmt.Printf("category: %s\n", results.Category)
    	fmt.Printf("district: %s\n", results.District)
    	fmt.Printf("asn: %s\n", results.Asn)
    	fmt.Printf("as: %s\n", results.As)
    	fmt.Printf("asdomain: %s\n", results.Asdomain)
    	fmt.Printf("asusagetype: %s\n", results.Asusagetype)
    	fmt.Printf("ascidr: %s\n", results.Ascidr)
    	fmt.Printf("api version: %s\n", ip2location.Api_version())
    	
    	db.Close()
    }
  8. Perform IP geolocation lookups with IP2Location

    master

    Use the IP2Location class to load a BIN database and retrieve geolocation data for specific IP addresses.

    1. Call OpenDB(binPath) with the file path to your IP2Location BIN database.
    2. Call Get_all(ipAddress) with the target IPv4 or IPv6 address to receive an array of geolocation details.
    // Example usage pattern
    // OpenDB(binPath)
    // Get_all(ipAddress)
  9. Manipulate IP addresses using the IP Tools class

    master

    The ip2location.OpenTools() method returns an instance of the IP Tools class, which provides utilities for:

    • Validation: IsIPv4(ip), IsIPv6(ip)
    • Conversion: IPv4ToDecimal(ip), IPv6ToDecimal(ip), DecimalToIPv4(ipnum), DecimalToIPv6(ipnum)
    • Formatting: CompressIPv6(ip), ExpandIPv6(ip)
    • CIDR Operations: IPv4ToCIDR(start, end), IPv6ToCIDR(start, end), CIDRToIPv4(cidr), CIDRToIPv6(cidr)
    package main
    
    import (
    	"github.com/ip2location/ip2location-go/v9"
    	"fmt"
    	"math/big"
    )
    
    func main() {
    	t := ip2location.OpenTools()
    	
    	ip := "8.8.8.8"
    	res := t.IsIPv4(ip)
    	
    	fmt.Printf("Is IPv4: %t\n", res)
    	
    	ipnum, err := t.IPv4ToDecimal(ip)
    	if err != nil {
    		fmt.Print(err)
    	} else {
    		fmt.Printf("IPNum: %v\n", ipnum)
    	}
    
    	ip2 := "2600:1f18:45b0:5b00:f5d8:4183:7710:ceec"
    	res2 := t.IsIPv6(ip2)
    	
    	fmt.Printf("Is IPv6: %t\n", res2)
    
    	ipnum2, err := t.IPv6ToDecimal(ip2)
    	if err != nil {
    		fmt.Print(err)
    	} else {
    		fmt.Printf("IPNum: %v\n", ipnum2)
    	}
    	
    	ipnum3 := big.NewInt(42534)
    	res3, err := t.DecimalToIPv4(ipnum3)
    	
    	if err != nil {
    		fmt.Print(err)
    	} else {
    		fmt.Printf("IPv4: %v\n", res3)
    	}
    	
    	ipnum4, ok := big.NewInt(0).SetString("22398978840339333967292465152", 10)
    	if ok {
    		res4, err := t.DecimalToIPv6(ipnum4)
    		if err != nil {
    			fmt.Print(err)
    		} else {
    			fmt.Printf("IPv6: %v\n", res4)
    		}
    	}
    	
    	ip3 := "2600:1f18:045b:005b:f5d8:0:000:ceec"
    	res5, err := t.CompressIPv6(ip3)
    	
    	if err != nil {
    		fmt.Print(err)
    	} else {
    		fmt.Printf("Compressed: %v\n", res5)
    	}
    	
    	ip4 := "::45b:05b:f5d8:0:000:ceec"
    	res6, err := t.ExpandIPv6(ip4)
    	
    	if err != nil {
    		fmt.Print(err)
    	} else {
    		fmt.Printf("Expanded: %v\n", res6)
    	}
    	
    	res7, err := t.IPv4ToCIDR("10.0.0.0", "10.10.2.255")
    	
    	if err != nil {
    		fmt.Print(err)
    	} else {
    		for _, element := range res7 {
    			fmt.Println(element)
    		}
    	}
    	
    	res8, err := t.IPv6ToCIDR("2001:4860:4860:0000:0000:0000:0000:8888", "2001:4860:4860:0000:eeee:ffff:ffff:ffff")
    	
    	if err != nil {
    		fmt.Print(err)
    	} else {
    		for _, element := range res8 {
    			fmt.Println(element)
    		}
    	}
    	
    	res9, err := t.CIDRToIPv4("123.245.99.13/26")
    	
    	if err != nil {
    		fmt.Print(err)
    	} else {
    		fmt.Printf("IPv4 Range: %v\n", res9)
    	}
    	
    	res10, err := t.CIDRToIPv6("2002:1234::abcd:ffff:c0a8:101/62")
    	
    	if err != nil {
    		fmt.Print(err)
    	} else {
    		fmt.Printf("IPv6 Range: %v\n", res10)
    	}
    }