UNPKG

@cmunroe/ip2asn

Version:

A class that works with https://ip2asn.ipinfo.app/.

85 lines (53 loc) 1.86 kB
"use strict"; const r = require('axios'); class ip2asn { constructor(options){ if(options && options.url){ this.url = options.url; } else{ this.url = 'https://ip2asn.ipinfo.app/lookup/'; } } get(ip){ return new Promise((success, failed) => { r.get(this.url + ip) .then(response => { success(response.data); }) .catch(error => { failed(error); }) }) } getPrimary(ip){ return new Promise((resolve, reject) => { this.get(ip) .then(response => { if(response.error){ throw response.error; } let primary = {'name': false, 'number': false, 'network': false, 'cidr': false}; response.announcedBy.forEach(announcement => { let cidr = parseInt(announcement.subnet.trim().split('/')[1]); let network = announcement.subnet.trim().split('/')[0]; if(cidr > primary.cidr){ primary.number = parseInt(announcement.asn) primary.name = announcement.name primary.network = network primary.cidr = cidr } }); return primary; }) .then((response) => { resolve(response); }) .catch((error) => { reject(error) }) }) } } module.exports = ip2asn