Maps IP addresses to country and AS info with low memory footprint.
IpMap class only uses ArrayBuffer and DataView and can probably work anywhere. I haven't checked.Warning: the lookup function uses a very naive parser that expects the addresses in the most basic form, 1.2.3.4 or a:b::c:d. If you're dealing with untrusted input, you should probably pass it through a proper parser first.
Install:
npm install ip-map
Fetch and process the latest dataset, and save it in the package directory:
npx ip-map update
# or
npx ip-map update cache/custom.bin # custom destination
Generate the blob using previously fetched TSV (any of)
npx ip-map parse ip2asn-combined.tsv.gz # save to default location
npx ip-map parse ip2asn-combined.tsv.gz cache/custom.bin
npx ip-map parse ip2asn-combined.tsv cache/custom.bin # can be unpacked
zcat ip2asn-combined.tsv.gz | npx ip-map parse - - > custom.bin # stdio
Lookup an address:
npx ip-map lookup 51.210.240.134
npx ip-map lookup 2001:abad:1dea:: praise.odin
Example output:
{
family: 4,
ip: '51.210.240.134',
int: 869462150,
as: { number: 16276, country: 'FR', description: 'OVH' },
range: {
family: 4,
first: '51.210.0.0',
last: '51.210.255.255',
firstInt: 869400576,
lastInt: 869466111,
size: 65536,
index: 73285
}
}
In Node:
import { loadIpMap } from 'ip-map';
const map = await loadIpMap(); // or loadIpMap('custom.bin');
const result = map.lookup('51.210.240.134');
const cc = result.as.country; // 'FR', may be null if the range is not assigned
Elsewhere:
import { IpMap } from '/dist/browser.js'; // or use a bundler, probably
const self = await fetch('https://4.this.computer').then(res => res.text());
const res = await fetch('/data/ip-map.bin');
const buffer = await res.arrayBuffer();
const map = new IpMap(buffer);
const result = map.lookup(self.trim());
console.log(result);
document.getElementById('result').textContent = JSON.stringify(result, null, '\t');
Public Domain / CC0