forked from jason5ng32/MyIP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmacchecker.js
78 lines (66 loc) · 2.96 KB
/
macchecker.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import { get } from 'https';
import { refererCheck } from '../common/referer-check.js';
const isValidMAC = (address) => {
const normalizedAddress = address.replace(/[:-]/g, '');
return normalizedAddress.length >= 6 && normalizedAddress.length <= 12 && /^[0-9A-Fa-f]+$/.test(normalizedAddress);
}
export default async (req, res) => {
// 限制只能从指定域名访问
const referer = req.headers.referer;
if (!refererCheck(referer)) {
return res.status(403).json({ error: referer ? 'Access denied' : 'What are you doing?' });
}
// 从请求中获取 IP 地址
let macAddress = req.query.mac;
if (!macAddress) {
return res.status(400).json({ error: 'No MAC address provided' });
} else {
macAddress = macAddress.replace(/:/g, '').replace(/-/g, '');
}
// 检查 IP 地址是否合法
if (!isValidMAC(macAddress)) {
return res.status(400).json({ error: 'Invalid MAC address' });
}
const token = process.env.MAC_LOOKUP_API_KEY || '';
const url_hasToken = `https://api.maclookup.app/v2/macs/${macAddress}?apiKey=${token}`;
const url_noToken = `https://api.maclookup.app/v2/macs/${macAddress}`;
const url = token ? url_hasToken : url_noToken;
get(url, apiRes => {
let data = '';
apiRes.on('data', chunk => data += chunk);
apiRes.on('end', async () => {
try {
const originalJson = JSON.parse(data);
if (originalJson.success !== true) {
return res.json({ success: false, error: originalJson.error || 'Data not found' });
}
const finalData = modifyData(originalJson);
res.json(finalData);
} catch (e) {
res.status(500).json({ error: 'Error parsing JSON' });
}
});
}).on('error', (e) => {
res.status(500).json({ error: e.message });
});
};
const modifyData = (data) => {
// 检查单播/多播以及本地/全球地址
const firstByte = parseInt(data.macPrefix.substring(0, 2), 16);
const isMulticast = (firstByte & 0x01) === 0x01;
const isLocal = (firstByte & 0x02) === 0x02;
data.isMulticast = isMulticast ? true : false;
data.isLocal = isLocal ? true : false;
data.isGlobal = !isLocal ? true : false;
data.isUnicast = !isMulticast ? true : false;
data.macPrefix = data.macPrefix ? data.macPrefix.match(/.{1,2}/g).join(':') : 'N/A';
data.company = data.company ? data.company : 'N/A';
data.country = data.country ? data.country : 'N/A';
data.address = data.address ? data.address : 'N/A';
data.updated = data.updated ? data.updated : 'N/A';
data.blockStart = data.blockStart ? data.blockStart.match(/.{1,2}/g).join(':') : 'N/A';
data.blockEnd = data.blockEnd ? data.blockEnd.match(/.{1,2}/g).join(':') : 'N/A';
data.blockSize = data.blockSize ? data.blockSize : 'N/A';
data.blockType = data.blockType ? data.blockType : 'N/A';
return data;
}