ip2region

repository·master·Indexed 41 days ago

https://github.com/yourtion/node-ip2region

A Node.js library for mapping IPv4 and IPv6 addresses to geographic regions and Internet Service Providers (ISP). Version 2.3.0 provides the IP2Region class for simplified lookups, as well as specialized Ipv4ToRegion and Ipv6ToRegion classes for granular control over database paths and raw result parsing.

Tokens
2.7K
Snippets
12
Records
13
Agent score
100%

What's inside ip2region

  1. Configure IP2Region database paths and IPv6 support

    master

    You can initialize the IP2Region instance with a configuration object to specify custom database paths or disable IPv6 support to reduce memory usage.

    Available configuration keys:

    • ipv4db: Path to the IPv4 database file.
    • ipv6db: Path to the IPv6 database file.
    • disableIpv6: Boolean flag to disable IPv6 lookup functionality.
    import IP2Region from "ip2region";
    
    const query = new IP2Region({
      ipv4db: "/tmp/db4.db",
      ipv6db: "/tmp/db6.db",
      disableIpv6: true,
    });
  2. Search IP address regions with IP2Region

    master

    Use the IP2Region class to perform IP-to-region lookups for both IPv4 and IPv6 addresses. The search method returns an object containing the country, province, city, and isp.

    import IP2Region from "ip2region";
    const query = new IP2Region();
    
    // IPv4 lookup
    const res = query.search('120.24.78.68');
    console.log(res);
    // Output: { country: '中国', province: '广东省', city: '深圳市', isp: '阿里云' }
    
    // IPv6 lookup
    const res2 = query.search('240e:47d:c20:1627:30a3:ba0d:a5e6:ec19');
    console.log(res2);
    // Output: { country: "中国", province: "广东省", city: "", isp: "中国电信" }
  3. Configure the Ipv4ToRegion database path

    master

    When instantiating Ipv4ToRegion, you can pass an optional dbPath string to the constructor.

    • If an absolute path is provided, it is used directly.
    • If a relative path is provided, it is resolved relative to the directory of the ipv4.ts file.
    • If no path is provided, it defaults to ../../data/ip2region.db.

    If the file does not exist at the resolved path, the constructor will throw an error: [Ipv4ToRegion] db file not exists : <path>.

    // Using an absolute path
    const locator = new Ipv4ToRegion('/absolute/path/to/ip2region.db');
    
    // Using a relative path
    const locator = new Ipv4ToRegion('./data/ip2region.db');
  4. Configure IP2Region with database paths

    master

    When instantiating the IP2Region class, you can provide an IP2RegionOpts object to specify the paths to your IPv4 and IPv6 database files. You can also choose to disable IPv6 support to save resources.

    Available options:

    • ipv4db (string): Path to the IPv4 database file.
    • ipv6db (string): Path to the IPv6 database file.
    • disableIpv6 (boolean): If set to true, the IPv6 engine will not be initialized.
    import IP2Region from 'node-ip2region';
    
    const ip2region = new IP2Region({
      ipv4db: './path/to/IPv4.mmdb',
      ipv6db: './path/to/IPv6.mmdb',
      disableIpv6: false
    });
  5. Use IP2Region to search IP location data

    master

    The IP2Region class provides two primary methods for looking up geographic information based on an IP address:

    1. search(ipaddr: string): Returns a simplified IP2RegionResult object containing country, province, city, and isp. This is the recommended method for most use cases.
    2. searchRaw(ipaddr: string, parse?: boolean): Returns the raw result from the underlying IPv4 or IPv6 engine. If parse is set to true (default), it returns a parsed object; if false, it returns the raw string format.

    Both methods return null if the IP address cannot be found in the database.

    import IP2Region from 'node-ip2region';
    
    const ip2region = new IP2Region({ ipv4db: './IPv4.mmdb' });
    
    // 1. Simplified search
    const result = ip2region.search('1.2.3.4');
    if (result) {
      console.log(result.country, result.province, result.city, result.isp);
    }
    
    // 2. Raw search (parsed)
    const rawResult = ip2region.searchRaw('1.2.3.4', true);
    
    // 3. Raw search (unparsed string)
    const rawString = ip2region.searchRaw('1.2.3.4', false);
  6. Configure Ipv6ToRegion with an IPv4 provider

    master

    To enable the Ipv6ToRegion class to handle IPv4-mapped addresses, 6to4, Teredo, or ISATAP addresses by falling back to an IPv4 database, use the setIpv4Ins method to inject an Ipv4ToRegion instance.

    const ipv6Lookup = new Ipv6ToRegion('../../data/ipv6wry.db');
    const ipv4Lookup = new Ipv4ToRegion('../../data/ipv4wry.db');
    
    // Link the IPv4 provider to the IPv6 lookup engine
    ipv6Lookup.setIpv4Ins(ipv4Lookup);
  7. Use the Ipv6ToRegion class for IPv6 lookups

    master

    The Ipv6ToRegion class provides methods to resolve IPv6 addresses to geographic information (country, province, city) and ISP data using a .db database file.

    To use it, instantiate the class with the path to your IPv6 database file. If you want to support IPv4-mapped IPv6 addresses or specific transition mechanisms (like 6to4 or Teredo) via IPv4 lookups, you should also provide an instance of Ipv4ToRegion using setIpv4Ins().

    Key methods:

    • search(ipaddr: string, parse?: boolean): The primary entry point. Takes an IPv6 string. If parse is true (default), it returns a structured Ipv6ToRegionResult. If false, it returns the raw Ipv6ToRegionRes object.
    • searchLong(ip6: bigint): Performs a lookup using a bigint representation of the IPv6 address.
    import Ipv6ToRegion from './lib/ipv6';
    
    // Initialize with the path to your IPv6 database
    const ipv6Lookup = new Ipv6ToRegion('../../data/ipv6wry.db');
    
    // Perform a lookup with parsed results
    const result = ipv6Lookup.search('2001:db8::1');
    
    if (result) {
      console.log(result.country, result.province, result.city, result.isp);
    }
  8. The search() method signature and return types

    master

    The search method performs the lookup. It accepts an IPv4 string and an optional parse boolean.

    Signatures:

    • search(ipaddr: string): Ipv4ToRegionResult (when parse is true or omitted)
    • search(ipaddr: string, parse: boolean): Ipv4ToRegionRes | null (when parse is false)

    Return Types:

    Ipv4ToRegionResult (Parsed):

    • id: number (City ID)
    • country: string
    • region: string
    • province: string
    • city: string
    • isp: string

    Ipv4ToRegionRes (Raw):

    • city: number
    • region: string (A pipe-delimited string: country|region|province|city|isp)

    If the IP address is invalid or not found in the database, the method returns null.

  9. Use the Ipv4ToRegion class for IPv4 lookups

    master

    The Ipv4ToRegion class is the primary interface for performing IP-to-region lookups using an IPv4 address. To use it, you must instantiate the class by providing the path to an ip2region.db file. If no path is provided, it defaults to ../../data/ip2region.db relative to the module.

    Once instantiated, you can use the .search() method to look up an IP address. The method supports two modes: returning a full parsed object or returning a raw result object.

    import Ipv4ToRegion from 'node-ip2region/src/lib/ipv4';
    
    // Initialize with the path to your database file
    const locator = new Ipv4ToRegion('./path/to/ip2region.db');
    
    // 1. Get full parsed results (default behavior)
    const result = locator.search('1.2.3.4');
    console.log(result.country, result.province, result.city);
    
    // 2. Get raw results (set parse to false)
    const rawResult = locator.search('1.2.3.4', false);
    // Returns { city: number, region: string } | null
  10. IP2RegionResult data structure

    master

    The search() method returns an object conforming to the IP2RegionResult interface, which provides the following geographic fields:

    • country: The country name.
    • province: The province or state name.
    • city: The city name.
    • isp: The Internet Service Provider name.
    interface IP2RegionResult {
      country: string;
      province: string;
      city: string;
      isp: string;
    }