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