| 1 | /** |
| 2 | * @module utils/ip |
| 3 | * @description IP utility functions |
| 4 | */ |
| 5 | import axios from 'axios' |
| 6 | import { Request } from 'express' |
| 7 | |
| 8 | /* 判断IP是不是内网 */ |
| 9 | function isLAN(ip: string) { |
| 10 | ip.toLowerCase() |
| 11 | if (ip === 'localhost') |
| 12 | return true |
| 13 | let a_ip = 0 |
| 14 | if (ip === '') |
| 15 | return false |
| 16 | const aNum = ip.split('.') |
| 17 | if (aNum.length !== 4) |
| 18 | return false |
| 19 | a_ip += Number.parseInt(aNum[0]) << 24 |
| 20 | a_ip += Number.parseInt(aNum[1]) << 16 |
| 21 | a_ip += Number.parseInt(aNum[2]) << 8 |
| 22 | a_ip += Number.parseInt(aNum[3]) << 0 |
| 23 | a_ip = (a_ip >> 16) & 0xFFFF |
| 24 | return ( |
| 25 | a_ip >> 8 === 0x7F |
| 26 | || a_ip >> 8 === 0xA |
| 27 | || a_ip === 0xC0A8 |
| 28 | || (a_ip >= 0xAC10 && a_ip <= 0xAC1F) |
| 29 | ) |
| 30 | } |
| 31 | |
| 32 | export function getIp(request: Request) { |
| 33 | const forwarded = request.headers['x-forwarded-for'] |
| 34 | || request.headers['X-Forwarded-For'] |
| 35 | || request.headers['X-Real-IP'] |
| 36 | || request.headers['x-real-ip'] |
| 37 | let ip: string | undefined |
| 38 | = (Array.isArray(forwarded) ? forwarded[0] : forwarded) |
| 39 | || request.ip |
| 40 | || request.socket?.remoteAddress |
| 41 | || undefined |
| 42 | if (ip && ip.split(',').length > 0) |
| 43 | ip = ip.split(',')[0] |
| 44 | |
| 45 | return ip |
| 46 | } |
| 47 | |
| 48 | export async function getIpAddress(ip: string) { |
| 49 | if (isLAN(ip)) |
| 50 | return '内网IP' |
| 51 | try { |
| 52 | let { data } = await axios.get( |
| 53 | `https://whois.pconline.com.cn/ipJson.jsp?ip=${ip}&json=true`, |
| 54 | { responseType: 'arraybuffer' }, |
| 55 | ) |
| 56 | data = new TextDecoder('gbk').decode(data) |
| 57 | data = JSON.parse(data) |
| 58 | return data.addr.trim().split(' ').at(0) |
| 59 | } |
| 60 | catch (e) { |
| 61 | return `第三方接口请求失败${e}` |
| 62 | } |
| 63 | } |
| 64 |