ipRegionLookup.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /**
  2. * 与 requestLog 相同:本地 ip2region.xdb,仅支持 IPv4。
  3. */
  4. const path = require('path')
  5. const ipSearcher = require('../../plugin/ip2region')
  6. let _searcher = null
  7. function getSearcher() {
  8. if (!_searcher) {
  9. _searcher = ipSearcher.newWithFileOnly(path.join(__dirname, '../../plugin/ip2region/ip2region.xdb'))
  10. }
  11. return _searcher
  12. }
  13. /**
  14. * @param {string|null|undefined} ip
  15. * @returns {Promise<string>} 可读属地,失败或非法为「未知」
  16. */
  17. async function lookupIpv4Region(ip) {
  18. const s = String(ip || '').trim()
  19. if (!s || !ipSearcher.isValidIp(s)) return '未知'
  20. try {
  21. const r = await getSearcher().search(s)
  22. const raw = r?.region
  23. if (!raw || typeof raw !== 'string') return '未知'
  24. return raw.split('|').filter(Boolean).join(' · ')
  25. } catch {
  26. return '未知'
  27. }
  28. }
  29. /**
  30. * 从 server 字段形如 host:port 取 IP
  31. */
  32. function extractIpFromServer(server) {
  33. if (!server || typeof server !== 'string') return null
  34. const host = server.split(':')[0].trim()
  35. return ipSearcher.isValidIp(host) ? host : null
  36. }
  37. module.exports = {
  38. lookupIpv4Region,
  39. extractIpFromServer
  40. }