ip2region - 是一个离线IP地址定位库和IP定位数据管理框架,同时支持 IPv4 和 IPv6。
npmjs ip2region官网地址
安装 ip2region
npm install ip2region --save
引入ip2region依赖 (使用CommonJS语法require引入)
const ip2region = require('ip2region').default
初始化IP查询器
// 初始化ip2region查询器
let searcher = null
/**
* 初始化IP查询器
*/
const initIpSearcher = () => {
if (!searcher) {
try {
// ip2region数据文件通常位于node_modules/ip2region/data/ip2region.db
const path = require('path')
// ./node_modules的具体写法需要参考当前文件相对于根目录的层级来调整 比如在一级子目录里可以写成../node_modules
const dbPath = path.join(__dirname, './node_modules/ip2region/data/ip2region.db')
searcher = new ip2region({ipv4db:dbPath})
} catch (err) {
console.error('初始化IP查询器失败:', err.message)
searcher = null
}
}
}
根据IP地址查询地理位置信息
/**
* 根据IP地址查询地理位置信息
* @param {string} ip - IP地址
* @returns {Promise<Object>} 地理位置信息
*/
const getIpLocation = async (ip) => {
// 忽略本地IP
if (ip === '::1' || ip === '127.0.0.1' || ip === '::ffff:127.0.0.1') {
return {
country: '本地',
region: '本地',
city: '本地',
isp: '本地网络'
}
}
// 初始化查询器
if (!searcher) {
initIpSearcher()
}
if (!searcher) {
return {
country: '',
region: '',
city: '',
isp: ''
}
}
try {
const result = await searcher.search(ip)
if (!result) return { country: '', region: '', city: '', isp: '' }
console.log(result)
// ip2region返回格式:国家|区域|省|市|ISP
const {country, region, province, city, isp} = result
return {
country: country !== '0' ? country : '',
region: province !== '0' ? province : (region !== '0' ? region : ''),
city: city !== '0' ? city : '',
isp: isp !== '0' ? isp : ''
}
} catch (err) {
console.error('IP地理位置查询失败:', err.message)
return {
country: '',
region: '',
city: '',
isp: ''
}
}
}
调用 IP地址定位功能
getIpLocation('61.163.151.198')
// 调用结果
// { country: '中国', province: '河南省', city: '郑州市', isp: '联通' }
将以上代码保存到ip.js中,使用命令node ip.js即可测试功能是否正常。